2010-06-08 118 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