简体   繁体   English

加载Google Map Geocoding API

[英]Google Map Geocoding API on load

I'm looking to adjust sample google map code found here https://developers.google.com/maps/documentation/javascript/geocoding so it geocodes the address on page loading. 我正在尝试调整在https://developers.google.com/maps/documentation/javascript/geocoding上找到的示例Google地图代码,以便对加载页面时的地址进行地理编码。 So no more fixed coordinates (already loaded from my view file) and should geocode by itself with no human interaction 因此,不再需要任何固定坐标(已经从我的视图文件中加载),并且无需人为干预即可进行地理编码

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}

function codeAddress() {
  var address = document.getElementById("address").value;
  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
    });
    } else {
    alert("Geocode was not successful for the following reason: " + status);
    }
  });
}

Thanks for your help. 谢谢你的帮助。

Not sure what you're asking here. 不知道您在这里问什么。 If you'd like the address to be geocoded when the page displays, there will need to be a value in the #address element: 如果您希望在页面显示时对地址进行地理编码,则#address元素中将需要一个值:

<input type="text" id="address" value="1600 Pennsylvania Ave NW  Washington, DC 20500">

...and then you simply call the initialize() and geocode() functions in window.onload function: ...然后您只需在window.onload函数中调用initialize()geocode()函数:

window.onload = function() {
    initialize();
    codeAddress();
}

Here's a jsFiddle demo: http://jsfiddle.net/fYbqe/ 这是一个jsFiddle演示: http : //jsfiddle.net/fYbqe/

EDIT Updated jsFiddle that makes it a bit easier to use a custom address: http://jsfiddle.net/fYbqe/1/ 编辑更新了jsFiddle,这使使用自定义地址更加容易: http : //jsfiddle.net/fYbqe/1/

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

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