繁体   English   中英

Google Maps地理编码有效,但方法不正确

[英]Google maps geocoding works but not the right way

我正在研究公司列表模板,并希望在Google地图中显示公司的位置。 这是我第一次使用Google Maps API,并且我的代码可以正常工作。 但是我知道我目前还没有完全正确的方法。

<script>

    var geocoder;
    var map;
    function initialize() {
      geocoder = new google.maps.Geocoder();
      var address = '<?php Here I give the address from my database by PHP ?>';
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location
          });
        }
      });  

      var latlng = new google.maps.LatLng(-34.397, 150.644);
      var mapOptions = {
        zoom: 16,
        center: latlng
      }
      map = new google.maps.Map(document.getElementById('big_map'), mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);   

</script>

<div id="big_map"></div>

我想通过results[0].geometry.location指定mapOptions center ,但无法正常工作。

就像我说的那样,我的代码有效,但是也许有人可以告诉我如何做得更好,因为我知道这不是100%正确的。

谢谢!

您是否尝试过更改获取“地图”的顺序,像这样...
第一:

var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
    zoom: 16,
    center: latlng
    }
map = new google.maps.Map(document.getElementById('big_map'), mapOptions);

第二:

geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    }
});

我使用了这段代码,并且有效:

 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <script> var geocoder; var map; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var mapOptions = { zoom: 16, center: latlng } map = new google.maps.Map(document.getElementById('big_map'), mapOptions); //var address = '<?php Here I give the address from my database by PHP ?>'; geocoder.geocode( { 'address': 'Somewhere'}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); }else { alert('Geocode was not successful for the following reason: ' + status); } }); } google.maps.event.addDomListener(window, 'load', initialize); </script> <div id="big_map" class="googleMapsMunicipios"></div> 

有关更多信息,请访问:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM