0

我正在尝试编写一个程序来查找地址的相应值 latLng,然后将其用于地图的中心。到目前为止,这是我的代码,但是我遇到的主要问题是从地理编码器中获取返回的值。

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps 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: 700px; height: 700px"></div> 

   <script type="text/javascript"> 

   var mapOptions = { 
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      center: new google.maps.LatLng(54.00, -3.00),
      zoom: 4
   };


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

   var address = '3410 Dr Martin Luther King Jr Blvd, New Bern, NC, US';


   geocoder.geocode({'address': address}, function(results, status) {
                                            if(status == google.maps.GeocoderStatus.OK) 
                                            {
                                                var bounds = new google.maps.LatLngBounds();
                                                document.write(bounds.extend(results[0].geometry.location));
                                                map.fitBounds(bounds);
                                                new google.maps.Marker(
                                            {
                                               position:results[0].geometry.location,
                                               map: map
                                             }
                                             );

                                         }

                                      }
                    );

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
   </script> 
</body> 
</html>
4

2 回答 2

1

你想在谷歌地图对象上设置界限。

var bounds = new google.maps.LatLngBounds();
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);

有关LatLngBounds的更多信息

map.fitBounds(bounds.getCenter())如果你有不止一个latlng,你可以做LatLngBounds

于 2011-11-11T15:34:32.907 回答
1

您想使用新的 latlng 在地图上调用 setCenter()。在您尝试执行此操作之前,我还会创建地图。

<script type="text/javascript"> 
  var geocoder = new google.maps.Geocoder();

  var address = '3410 Dr Martin Luther King Jr Blvd, New Bern, NC, US';

  var mapOptions = { 
          mapTypeId: google.maps.MapTypeId.TERRAIN,
          center: new google.maps.LatLng(54.00, -3.00),
          zoom: 5
  };

   var map = new google.maps.Map(document.getElementById("map"), mapOptions);

   geocoder.geocode({'address': address}, function(results, status) {
          if(status == google.maps.GeocoderStatus.OK) 
          {
               result = results[0].geometry.location;
               console.log(result);

               map.setCenter(result);
           }
   });
   </script>
于 2011-11-11T15:40:40.550 回答