2010-06-08 154 views
3

我想从两个地址点用Google Maps JavaScript API绘制测地多折线。谷歌地图地理编码(地址GLatLng)

var polyOptions = {geodesic:true}; 
var polyline = new GPolyline([ 
    new GLatLng(), 
    new GLatLng() 
    ], "#f36c25", 5, 0.8, polyOptions 
); 

map.addOverlay(polyline); 

if (GBrowserIsCompatible()) { 
    map.addOverlay(polyline); 
} 

有人能告诉我如何动态地址码地址到GLatLng坐标?阅读Google's API documentation后我有些困惑。

回答

2

你可能想看看下面的例子。首先它尝试地理编码address1。如果成功,它会尝试对地址address2进行地理编码。如果两个成功,它绘出了测地折线在两个坐标之间,以及两个标志:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps API Geocoding Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 500px; height: 400px;"></div> 

    <script type="text/javascript"> 
    var address1 = 'London, UK'; 
    var address2 = 'New York, US'; 

    var map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 2, 
     center: new google.maps.LatLng(35.00, -25.00), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    var gc = new google.maps.Geocoder(); 

    gc.geocode({'address': address1}, function (res1, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     gc.geocode({'address': address2}, function (res2, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
      new google.maps.Marker({ 
       position: res1[0].geometry.location, 
       map: map 
      }); 

      new google.maps.Marker({ 
       position: res2[0].geometry.location, 
       map: map 
      }); 

      new google.maps.Polyline({ 
       path: [ 
       res1[0].geometry.location, 
       res2[0].geometry.location 
       ], 
       strokeColor: '#FF0000', 
       geodesic: true, 
       map: map 
      }); 
      } 
     }); 
     }    
    }); 

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

截图:

Google Maps API Geocoding Demo

+0

如果你有你的地图上十亿个像我这样做。这看起来很酷:'var color ='#'+(Math.random()* 0xFFFFFF << 0).toString(16); \t \t \t \t \t \t新google.maps.Polyline({ \t \t \t \t路径: \t \t \t \t initialLocation, \t \t \t \t current_point \t \t \t \t], \t \t \t \t则strokeColor:颜色, \t \t \t \t短程线:真, \t \t \t \t图:图 \t \t \t \t});' – 2012-10-25 18:44:16