Google maps API - 按地址javascript添加标记 [英] Google maps API - add marker by address javascript

查看:105
本文介绍了Google maps API - 按地址javascript添加标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have database of places with addresses and I want to add markers on google maps.

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

It shows only the default marker, seems like the geocoder.geocode() does nothing. For an example I'm trying to add a marker on " New York City", with no success.

<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>


推荐答案

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

The reason why you are not getting the expected result is because there is incorrect codes placement in the example you provided. You are trying to get a new instance of Google Maps API Geocoder before Google Maps is fully loaded. Hence, Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined. You should get a new instance of Google Maps API Geocoder inside the initMap() function.

您可以检查 地图JavaScript API地理编码
了解详情。

You can check Maps JavaScript API Geocoding to learn more.

您还可以查看 地理编码地址时的最佳做法

You can also check Best Practices When Geocoding Addresses.

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

Please also note that you should not include your API_KEY when posting Google Maps APi related questions.

以下是整个代码:

<!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>

现场演示 这里

Live demo here.

希望有所帮助!

这篇关于Google maps API - 按地址javascript添加标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆