【问题标题】:geocode a marker in Google Maps在 Google 地图中对标记进行地理编码
【发布时间】:2014-05-21 12:44:03
【问题描述】:

我在此站点上漫游,以获取有关对标记进行地理编码的任何信息。但是,我已经尝试了一些答案,但我没有设法让它工作(在编码方面我是一个业余爱好者),所以有人可以帮我对我的标记进行地理编码吗?显然,使用此代码时缺少标记。在这种情况下,我需要对邮政编码进行地理编码,即邮政编码 1058JA。提前致谢!

var geocoder;
var map;
var Postcode;

Postcode = '1058JA';

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(52.368465, 4.903921);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);


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

        geocoder.geocode( {'address': document.getElementById("address").value },
          function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              Postcode = results[0].geometry.location;
              map = new google.maps.Map(document.getElementById("map_canvas"),
              {
                center: Postcode,
                zoom: 11,
                mapTypeId: google.maps.MapTypeId.ROADMAP
              });
            var marker=new google.maps.Marker({
        position:results[0].geometry.location,
        });
        marker.setMap(map);
            } 
            else {
              document.getElementById("address").value = status;
            }
          }
        );

      }  
}
google.maps.event.addDomListener(window, 'load', initialize);

【问题讨论】:

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


【解决方案1】:

您的代码有一些问题。

1) codeAddress 永远不会被调用(正如 Anto Jurković 所说)。

2) 如果曾经调用过,则会在 codeAddress 中创建一个新的 map 实例,这是多余的。

3) 当您将 Postcode 指定为代码顶部的字符串时,地理编码器正在寻找输入元素的值。

你的代码应该是这样的:

var geocoder;
var map;
var Postcode;

Postcode = '1058JA';

function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(52.368465, 4.903921);
    var mapOptions = {
        zoom: 8,
        center: latlng
    }
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    codeAddress();
}

function codeAddress() {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': Postcode }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
            });
            marker.setMap(map);
        } else {
            document.getElementById("address").value = status;
        }
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多