如何设置基于街道地址的谷歌地图中心 [英] How to set center of google map based on street address

查看:104
本文介绍了如何设置基于街道地址的谷歌地图中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Google Maps API和地理编码服务。我遵循这个教程,它很棒。



现在我希望能够创建一个基于位置(Vancvouer,BC)的中心地图,而不是创建地图时所需的纬度和经度。



我试图做的是使用名为initMap()的回调函数来初始化地图,并且在该函数中,我将创建一个Geocoder对象,以基于位置获取lang和long。 (Vancvouer,BC)。

这是我的initMap()函数:

 函数initMap(){

var geocoder1 = new google.maps.Geocoder();
var center = getCenter(geocoder1,'Vancouver,BC');

if(center!= null){
alert(center [0] .geometry.location);


var map = new google.maps.Map(document.getElementById('map'),{
zoom:8,
center:{lat: -34.397,lng:150.644}
});

$ / code>

这就是我如何根据地址获得lang和long:

  function getCenter(geocoder,address){
geocoder.geocode({'address':address},function(results,status ){
if(status === google.maps.GeocoderStatus.OK){
console.log(results);
var result = results [0] .geometry.location.toJSON( );
返回结果;
} else {
alert('由于以下原因,Geocode不成功:'+ status');
//返回null;
}
});
}

这会返回一个带有我想要的lat和lang的JSON对象,但是当我尝试使用if语句中心在initMap()中访问它的值始终未定义。



一旦我能够获得中心的价值,我相信我可以轻松设置中心,但为什么我没有获得这些值?



我认为它是一个范围和回调函数的问题,但无法弄清楚。被卡住了一段时间,以为我会伸出援手。



谢谢,

Matt

让我知道你是否需要其他信息。第一篇文章是关于stackoverflow的...

解决方案

geocoder是异步的,你不能从异步回调函数中返回任何东西。您需要在回调函数中使用返回的数据:/ b>

 函数setCenter(geocoder,address){ 
geocoder.geocode({
'address':address
},function(results,status){
if(status === google.maps.GeocoderStatus.OK){
var map = new google.maps.Map(document.getElementById('map'),{
zoom:8,
center:results [0] .geometry.location
});
} else {
alert('由于以下原因,Geocode不成功:'+ status';
//返回null;
}
} );
}

概念证明小提琴



代码段:

 函数initMap(){var geocoder1 = new google.maps.Geocoder(); setCenter(geocoder1,'Vancouver,BC');} function setCenter(geocoder,address){geocoder.geocode({'address':address},function(results,status){if(status === google.maps.GeocoderStatus .OK){var map = new google.maps.Map(document.getElementById('map'),{zoom:8,center:results [0] .geometry.location});} else {alert('Geocode was not成功的原因如下:'+ status); // return null;}});} google.maps.event.addDomListener(window,load,initMap);  

html,body,#map {height:100%;宽度:100%; margin:0px; < script src =https://


I have just started working with the Google Maps API and Geocoding Service. I followed this tutorial and it was great.

Now I want to be able to create a map with a center based on a location ( "Vancvouer, BC" ) as opposed to latitude and longtitude as required when creating the map.

What I am trying to do is use a callback function named "initMap()" to initialize the map, and in that function I am creating a Geocoder object to get lang and long based on a location. ( "Vancvouer, BC" ).

Here's my initMap() function:

function initMap() {

    var geocoder1 = new google.maps.Geocoder();
    var center = getCenter(geocoder1, 'Vancouver, BC');

    if(center != null) {
        alert(center[0].geometry.location);
    }

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: {lat: -34.397, lng: 150.644}
    });
}

This is how I am getting lang and long based on address:

function getCenter(geocoder, address) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            console.log(results);
            var result = results[0].geometry.location.toJSON();
            return result;
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
            // return null;
        }
    });
}

This will return a JSON object with the lat and lang I want, but when I try to access its values in initMap() using the if statement center is always undefined.

Once I am able to get the value for center I believe I would be able to set the center easy enough, but why I am not getting these values?

I think its a problem with scope and callback functions, but cant figure it out. Been stuck for a while, thought I'd reach out for help.

Thanks,

Matt

P.S. Let me know if you need any other info. First post on stackoverflow...

解决方案

The geocoder is asynchronous, you can't return anything from an asynchronous callback function. You need to use the returned data inside the callback function where/when it is available:

function setCenter(geocoder, address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
      // return null;
    }
  });
}

proof of concept fiddle

code snippet:

function initMap() {

  var geocoder1 = new google.maps.Geocoder();
  setCenter(geocoder1, 'Vancouver, BC');
}

function setCenter(geocoder, address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
      // return null;
    }
  });
}
google.maps.event.addDomListener(window, "load", initMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>

<div id="map"></div>

这篇关于如何设置基于街道地址的谷歌地图中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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