谷歌地图地理编码(地址到GLatLng)

3

我正在尝试使用Google Maps JavaScript API从两个地址点绘制一个地球测地线折线。

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坐标吗?在阅读谷歌API文档后,我有些困惑。

1个回答

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 地理编码演示


如果你的地图上有十亿个点,就像我一样。这看起来非常酷:var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16); new google.maps.Polyline({ path: [ initialLocation, current_point ], strokeColor: color, geodesic: true, map: map }); - John Riselvato

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接