Google maps API - 按地址javascript添加标记

时间:2017-10-21 22:24:39

标签: javascript google-maps google-maps-api-3 geocoding

我有地址数据库,我想在谷歌地图上添加标记。

它只显示默认标记,看起来像geocoder.geocode()什么都不做。举个例子,我试图在"上添加一个标记。纽约市",但没有成功。

<script>
    var geocoder;
    var map;
    var address = "new york city";
    geocoder = new google.maps.Geocoder();
    function initMap() {
        var uluru = { lat: -25.363, lng: 131.044 };
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 4,
            center: uluru
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
        codeAddress(address);

    }

    function codeAddress(address) {

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == 'OK') {
                    var marker = new google.maps.Marker({
                    position: address,
                    map: map
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }


</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
    async defer></script>

2 个答案:

答案 0 :(得分:13)

您未获得预期结果的原因是您提供的示例中存在错误的代码放置。您正在尝试在Google地图完全加载之前获取Google Maps API地理编码器的新实例。因此,由于未捕获的ReferenceError:Google未定义,Google Maps API地理编码器无法正常工作。您应该在initMap()函数中获得一个新的Google Maps API Geocoder实例。

您可以查看 Maps JavaScript API Geocoding 了解详情。

您还可以查看 Best Practices When Geocoding Addresses

另请注意,在发布与Google Maps APi相关的问题时,您不应包含API_KEY。

以下是整个代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Geocoding service</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var geocoder;
      var map;
      var address = "new york city";
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat: -34.397, lng: 150.644}
        });
        geocoder = new google.maps.Geocoder();
        codeAddress(geocoder, map);
      }

      function codeAddress(geocoder, map) {
        geocoder.geocode({'address': address}, function(results, status) {
          if (status === '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);
          }
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

现场演示 here

希望它有所帮助!

答案 1 :(得分:2)

您的代码中存在多个错误。通常情况下,现在应该看起来不错了:

var geocoder;
var map;
var address = "new york city";

function initMap() {
    geocoder = new google.maps.Geocoder();

    var uluru = { lat: -25.363, lng: 131.044 };
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        center: uluru
    });
    var marker = new google.maps.Marker({
        position: uluru,
        map: map
    });
    codeAddress(address);

}

function codeAddress(address) {

    geocoder.geocode({ 'address': address }, function (results, status) {
        console.log(results);
        var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
        console.log (latLng);
        if (status == 'OK') {
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
            console.log (map);
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

这是您的错误列表:

  • 当Google Maps api完全加载时,您必须初始化地理编码。这意味着您必须在geocoder = new google.maps.Geocoder();
  • 中添加以下代码:initMap ()
  • 初始化地图时,您必须引用全局变量。在您的代码中,您将在函数中创建一个新的变量映射。但是,你必须通过全局的变量映射。
  • 当您想要获取地理编码器结果的位置时,您必须通过以下代码行:results[0].geometry.location.lat ()

您可以参考documentation

如果您有任何疑问,请告诉我。