简体   繁体   English

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

[英]Google maps API - add marker by address javascript

I have database of places with addresses and I want to add markers on google maps. 我有地址数据库,我想在谷歌地图上添加标记。

It shows only the default marker, seems like the geocoder.geocode() does nothing. 它只显示默认标记,看起来像geocoder.geocode()什么都不做。 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>

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. 您正在尝试在Google地图完全加载之前获取Google Maps API地理编码器的新实例。 Hence, Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined . 因此,由于此未捕获的ReferenceError ,Google Maps API地理编码器将无法正常工作:未定义Google You should get a new instance of Google Maps API Geocoder inside the initMap() function. 您应该在initMap()函数中获得一个新的Google Maps API Geocoder实例。

You can check Maps JavaScript API Geocoding to learn more. 您可以查看Maps JavaScript API地理编码以了解详情。

You can also check Best Practices When Geocoding Addresses . 您还可以查看地理编码地址时的最佳做法

Please also note that you should not include your API_KEY when posting Google Maps APi related questions. 另请注意,发布Google Maps APi相关问题时,不应包含API_KEY。

Here's the whole code: 这是整个代码:

<!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 . 现场演示这里

Hope it helps! 希望能帮助到你!

There were several errors in your code. 您的代码中存在多个错误。 Normally, it should looks OK now: 通常,它现在应该看起来不错:

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);
        }
    });
}

This is a list of your errors: 这是您的错误列表:

  • You have to initialize your geocode when the google maps api is fully loaded. 当Google Maps api完全加载时,您必须初始化地理编码。 It means that you have to put this line of code: geocoder = new google.maps.Geocoder(); 这意味着您必须使用以下代码行: geocoder = new google.maps.Geocoder(); in the initMap () . initMap ()
  • When you initialize the map you have to refer to a global variable. 初始化地图时,您必须引用全局变量。 In your code, you create a new variable map in your function. 在您的代码中,您将在函数中创建一个新的变量映射。 But, you have to pass by the global's variable map. 但是,你必须通过全局的变量映射。
  • When, you want to get the position of the geocoder's result, you have to pass by this line of code: results[0].geometry.location.lat () . 当你想获得地理编码器结果的位置时,你必须通过这行代码: results[0].geometry.location.lat ()

You may refer to the documentation . 您可以参考文档

Tell me if you have some questions. 如果您有疑问,请告诉我。

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

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