+-
Google Maps API V3学习(例子不断增加中)

以前公司内网中用v2版本做过一个基于google map开发的班车路线,与时俱进一把,现在v3已经出来就学习一下吧,正好项目有所需要,新发布的Google Maps API V3。


      V3相对于V2存在许多改变,比如在地图的加载上,尤其是手机浏览器访问的速度更快了(参考自其说明文档)。从开发上,V3版不再需要获取API的Key(以往每部署一套程序,都得去申请一个key,麻烦的很),V3所有都在google.maps.*的命名空间下,没有以“G”为前缀的全局变量了,所以以往的v2代码都不能复用,需要进行一定的修改。    

一、js引用:

 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=zh-CN"></script 
说明:其中sensor这个参数是必须的,如果应用程序是通过使用的传感器(如GPS定位仪)来确定用户的位置,就设为true。一般我们不做移动设备开发的话都设置为false。我们可以通过设置语言(language)或者是区域代码(region)来本地化地图应用,这两个参数是可选的。

 

二、例子:

 1、 hello world :



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml">   
<head runat="server">   
    <title>Google 地图 JavaScript API 示例: 简单的地图</title>   
    <%– 加载 Google 地图 API JavaScript–%>   
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=zh-CN"></script>   
    <script type="text/javascript">   
    var map;   
    //地图初始化   
    function initialize() {   
        var mapOptions = {         
            zoom: 14,                //缩放级别     
            center: new google.maps.LatLng(31.838463501293745, 117.17588437182617),       //将地图的中心设置为指定的地理点 可以使用 0(最低缩放级别,在地图上可以看到整个世界)到 19(最高缩放级别,可以看到独立建筑物)之间的缩放级别   
            mapTypeId: google.maps.MapTypeId.SATELLITE,   //ROADMAP-默认视图 SATELLITE-显示Google地球卫星图像 HYBRID-混合显示普通视图和卫星视图 TERRAIN-地形图    
            scaleControl: true,    //比例尺   
            mapTypeControl: true,       
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}   
        };   
        map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);//编写 JavaScript 函数创建“map”对象   
    }     
   </script>   
</head>   
<body onload="initialize()">   
    <form id="form1" runat="server">   
    <%–创建名为“map_canvas”的 div 元素来包含地图–%>   
    <div id="map_canvas" style="width: 800px; height: 600px">   
    </div>   
    </form>   
</body>   
</html>

2、添加marker ,同时显示marker点的坐标和信息


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>makePoint</title>
</head>

<body onload="initialize()">
<h1>makePoint</h1>
<div id="map_canvas" style="width : 800px; height : 600px;"></div>
<div style="text-align:left;display:none;">
	<form id="oa" method="post" action="/neweb/oa/admin/manager/BusLine.do">
    <b> 班车路线:</b>
    <br/>
    <b> 是否停靠:</b>
    <label onclick="tkd_hide();">
      <input name="is_stop" type="radio" id="is_stop1" value="0" />
      否:路线点</label>
    <label onclick="tkd_show();">
      <input type="radio" name="is_stop" id="is_stop2" value="1" checked="checked" />
      是:停靠点</label>
    <br/>
    <b>  排序值:</b>
    <input type="text" name="order_lever" size="32" maxlength="4" value="0" />
    <br/>
    <b> 地图坐标:</b>
	<span id="g_lat_lng_span"></span>
    <br/>
    <b>  停靠点:</b>
    <input type="text" name="stop_station" size="32" maxlength="32" />
    <br/>
    <b>停靠点说明:</b>
	<span id="stop_station_desc_span"></span>
    <br/>
    <b>   路段:</b>
    <input type="text" name="road_section" size="32" maxlength="32" />
    <br/>
    <b> 停靠时间:</b>
    <input type="text" name="stop_time" size="32" maxlength="16" />
    <br/>
    <b> 公交站牌:</b>
    <input type="text" name="bus_station" size="32" maxlength="32" />
    <br/>
    <b> 附近标志:</b>
    <input type="text" name="typical_sign" size="32" maxlength="32" />
    <br/>
    <b>      &nbsp;</b>
    <input type="submit" value=" 保存 " />
    <input type="reset" value=" 重填 " />
	</form>
</div>
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript">

var map;
var marker;
var infowindow;
var geocoder;
var markersArray = [];
function initialize() {
  geocoder = new google.maps.Geocoder();
  var myLatlng = new google.maps.LatLng(31.838463501293745,117.17588437182617);
  var myOptions = {
    zoom: 13,
    center: myLatlng,
	navigationControl: true,
	scaleControl: true,
	streetViewControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });


}
  

function placeMarker(location) {
  clearOverlays(infowindow);
  var clickedLocation = new google.maps.LatLng(location);
  marker = new google.maps.Marker({
      position: location, 
      map: map
  });
  markersArray.push(marker);

  map.setCenter(location);

  var point = location.lat() + "," + location.lng();
  var address;
  //prompt("坐标",location.lat() + "," + location.lng());

  $("input[name='g_lat_lng']").val(point);
  $("#g_lat_lng_span").empty().append(' <input type="text" name="g_lat_lng" size="32" maxlength="32" value='+ point + '></input>');
  $("#stop_station_desc_span").empty().append(' <input type="text" name="stop_station_desc" size="32" maxlength="32"></input>');
  if (geocoder) {
		geocoder.geocode({'location': location}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
			 if (results[0]) {
				// alert(results[0].formatted_address);
				address = results[0].formatted_address;
				$("input[name='stop_station_desc']").val(address);
                
				$("#stop_station_desc_span").empty().append(' <input type="text" name="stop_station_desc" size="32" maxlength="32" value='+ address +'></input>');
			 }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
  }

  //alert($("#oa").html());
  
  var table = '\<form id="bus_form" method="post" action="/oa/admin/manager/BusLine.do" onsubmit="bus_save();return false;">'
    	    + $("#oa").html() +
    	    '\<\/form>'
  infowindow = new google.maps.InfoWindow(
    {   content: table,
        size: new google.maps.Size(50,50),
        position: location
    });
  infowindow.open(map);

  //alert( $("input[name='g_lat_lng']", "#oa").val());
  //alert( $("input[name='stop_station_desc']", "#oa").val());

}

function bus_save(){
	alert("停靠点添加成功!");
	marker.setMap(null);
	infowindow.close();
}

  // Deletes all markers in the array by removing references to them
 function clearOverlays(infowindow) {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
	if (infowindow){
		infowindow.close();
	}
  }

</script>
</body>
</html>


3、计算点点之间的距离【2010-08-03】(Extended.js下面有下载)



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>计算点点距离</title>
</head>

<body onload="initialize()">
<h1>计算点点距离</h1>
<div id="map_canvas" style="width : 800px; height : 600px;"></div>
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript" src="Extended.js"></script> 


<div id="console">总路程:<span id="total_km"></span></div>
<input type='button' id='clearOverlays' onclick='clearOverlays();' value='重新计算'></input>
<script type="text/javascript">

var map;
var marker;
var geocoder;
var markersArray = [];
var polyline;
var polylineArray =[];
var infowindowLevel = 0;

function initialize() {
	geocoder = new google.maps.Geocoder();
	var myLatlng = new google.maps.LatLng(31.838463501293745, 117.17588437182617);
	var myOptions = {
		zoom: 13,
		center: myLatlng,
		navigationControl: true,
		scaleControl: true,
		streetViewControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	google.maps.event.addListener(map, 'click',
	function(event) {
		addMarker(event.latLng);
	}); 
} 

//画线,计算线的距离
function drawOverlay() {
	var flightPlanCoordinates = [];
	if (markersArray) {
		for (i in markersArray) {
			flightPlanCoordinates.push(markersArray[i].getPosition());
		}
	}
	polyline = new google.maps.Polyline({
		path: flightPlanCoordinates,
		strokeColor: "#FF0000",
		strokeOpacity: 1.0,
		strokeWeight: 2
	});

	if (polylineArray) {
		for (i in polylineArray) {
			polylineArray[i].setMap(null);
		}
		polylineArray = [];
	}
	polyline.setMap(map);

	$("#total_km").empty().text((polyline.getLength()/1000).toFixed(3) + "km");
	polylineArray.push(polyline);
}



//增加点
function addMarker(location) {
	marker = new google.maps.Marker({
		position: location,
		map: map,
		icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
		draggable: true
	});
	markersArray.push(marker);

	drawOverlay();

	google.maps.event.addListener(marker, 'drag', function() {
		drawOverlay();
	});

}



//清空地图
function clearOverlays(infowindow) {
	if (markersArray) {
		for (i in markersArray) {
			markersArray[i].setMap(null);
		}
		markersArray.length = 0;
	}

	if (polylineArray) {
		for (i in polylineArray) {
			polylineArray[i].setMap(null);
		}
		polylineArray = [];
	}

	$("#total_km").empty();
}


</script>
</body>
</html>