HTML / JavaScript地理位置未定义

时间:2017-03-05 18:27:54

标签: javascript html google-maps geolocation

这是我的功能:

function getLocation() {        
    if (navigator.geolocation) {  
      navigator.geolocation.getCurrentPosition(function (position) {                  
        var initialLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };            
        map.setCenter(initialLocation);
      });
      var mapProp= {     
        zoom:12,     
      };         

      map=new google.maps.Map(document.getElementById("googleMap"),mapProp);         
      infowindow = new google.maps.InfoWindow();                              
      var pyr = new google.maps.LatLng(initialLocation);
      var request = {              
      location: pyr,        
      radius: '49999',           
      query: 'gym'             
      };                
      var service = new google.maps.places.PlacesService(map);               
      service.textSearch(request, callback);
   }
}

我想将地图置于用户所在位置(有效),然后我想搜索附近的健身房并将其显示为标记。

我使用map.setCenter(initialLocation);将地图居中。我尝试使用

设置搜索位置
var pyr = new google.maps.LatLng(initialLocation);
location: pyr

var pyr = initialLocation;
location: pyr

两者都失败了,如果我打印出initialLocation,它会给出undefined,尽管map正确地居中。帮助

1 个答案:

答案 0 :(得分:0)

地理定位服务是异步的,您需要使用返回的值来在回调函数中进行搜索,在何时/何时可用。

function getLocation() {        
  if (navigator.geolocation) {  
    navigator.geolocation.getCurrentPosition(function (position) {                  
      var initialLocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };            
      map.setCenter(initialLocation);
      var service = new google.maps.places.PlacesService(map);    
      var pyr = initialLocation;
     var request = {              
        location: pyr,        
        radius: '49999',           
        query: 'gym'             
     };                  
     service.textSearch(request, callback);
  });
  var mapProp= {     
    zoom:12,     
  };         

  map=new google.maps.Map(document.getElementById("googleMap"),mapProp);         
  infowindow = new google.maps.InfoWindow();                              
}