Google Maps API简易教程(一)

 一、API Key

   使用Google API,必须要从Google 那里获取一个免费的API 键。获取过程如下:

 (1)用google账户登陆https://code.google.com/apis/console/,点击“Create Project”按钮,

 (2)在服务列表中,找到Google Maps API v3,点击off,使其处于on的状态。

 (3)点击左边菜单的"API Access",它将询问你创建一个OAuth 2.0 client id(简单应用不必)

 (4)在下一屏幕中,将会显示API key的相关信息。

   备注:保存好API key!(在所有Google Maps APP中必须使用)

二、创建一个基本的Google Map

  为了简单起见,下面创建一个以英国伦敦为中心的Google Map。相关代码如下:

 

 
 
 
  1.   <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4. <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"> 
  5. </script> 
  6. <script> 
  7. function initialize() 
  8. var mapProp = { 
  9.   center:new google.maps.LatLng(51.508742,-0.120850), 
  10.   zoom:5, 
  11.   mapTypeId:google.maps.MapTypeId.ROADMAP 
  12.   }; 
  13. var map=new google.maps.Map(document.getElementById("googleMap") 
  14.   ,mapProp); 
  15. google.maps.event.addDomListener(window, 'load', initialize); 
  16. </script> 
  17. </head> 
  18. <body> 
  19. <div id="googleMap" style="width:500px;height:380px;"></div> 
  20. </body> 
  21. </html> 

备注:script中的key为上一节注册的API key。

三、Google Maps-Overlays

  Overlays是地图上的对象,对应着相关的经度/维度坐标。比较常用的有以下几种:

  .Marker-地图上单个位置。

  .Polyline-地图上一系列直线。

  .Polygon-地图上一系列直线,并且处于封闭的形状。

  .Circle 和 Rectangle。

  .info Windows-地图上,上升气球里显示内容。

 (1)加入一个Marker

   Marker构造函数创建一个标签(注意:必须先设置位置属性)。

   接着,使用setMap()方法加入marker到map中。

   代码如下:

 

 
 
 
  1.  var marker=new google.maps.Marker({ 
  2. position:myCenter, 
  3. }); 
  4.  
  5.  marker.setMap(map); 

 (2)使Marker动起来

  代码如下:

 
 
 
  1.  marker=new google.maps.Marker({ 
  2.   position:myCenter, 
  3.   animation:google.maps.Animation.BOUNCE 
  4.   }); 
  5. marker.setMap(map); 

(3)Google Maps-Polyline

   Polyline是通过一系列排好序的坐标的线。它支持一下属性:

   .path-具体化线的几个经度/纬度坐标。

   .strokeColor-为线设置一个16进制的颜色值。

   .strokeOpacity-为线设置透明度(值介入0.0和1.0之间)

   .strokeWeight-具体化线的权重。

   .editable-定义用户是否可编辑改线。

 代码如下:

 

 
 
 
  1. var myTrip = [stavanger,amsterdam,london]; 
  2. var flightPath = new google.maps.Polyline({ 
  3.   path:myTrip, 
  4.   strokeColor:"#0000FF"
  5.   strokeOpacity:0.8, 
  6.   strokeWeight:2 
  7. }); 

(4)Circle的用法

  circle支持如下属性:

  .center-circle的中心。

  .radius-具体圆的半径,以米为单位。

  .strokeColor-为环绕圆的线设置一个16进制的颜色。

  .strokeOpacity-为环绕圆的线设置透明度。

  .strokeWeight-为环绕圆的线设置权重,单位像素。

  .fillColor-为圆的内部区域设置一个16进制颜色值。

  .fillOpacity-为圆的内部填充颜色设置透明度。

  .editable-解释同上。

 代码如下:

 

 
 
 
  1. var myCity = new google.maps.Circle({ 
  2.   center:amsterdam, 
  3.   radius:20000, 
  4.   strokeColor:"#0000FF"
  5.   strokeOpacity:0.8, 
  6.   strokeWeight:2, 
  7.   fillColor:"#0000FF"
  8.   fillOpacity:0.4 
  9. }); 

(5)InfoWindow的使用

  InfoWindow是为Marker对象显示相关文本信息:

  例子代码如下:

 

 
 
 
  1. var infowindow = new google.maps.InfoWindow({ 
  2.   content:"Hello World!" 
  3.   }); 
  4. infowindow.open(map,marker); 

原文链接:http://www.cnblogs.com/williamcai/archive/2013/02/27/Technical_enthusiasts.html

THE END