【问题标题】:Accessing positions of marker and places with Google Maps API JS使用 Google Maps API JS 访问标记和地点的位置
【发布时间】:2020-03-23 01:40:13
【问题描述】:

我在访问标记和地点的地理位置时遇到问题。

基本上,我正在为在地图中心有一个位置的用户创建一个标记。然后我运行geolocation.watchPosition 函数,在其中我更新userMarker 位置。因此,在watchPosition 完成的每一个滴答声中,我都会将 userMarker 的位置更新为其当前位置。我也在用一些places 做一个非常相似的事情,我在给定的半径内搜索。搜索以watchPosition 的每个刻度运行,并为每个place 提供标记。

从视觉上看,所有标记都位于正确的位置并在正确的位置更新,因此它们的位置正确。问题是,当我尝试使用console.log(userMarker.getPosition()) 将标记的位置打印到控制台时,我返回了标记的LatLng 对象,但它是空的,看起来像这样:_.E {}

我基本上只是想知道我在访问标记位置时做错了什么以及为什么?这不仅仅是物体的样子,肯定是我做错了。

下面是部分代码:

function updateMap(){
  //navigator is passed a callback to handle return position
  navigator.geolocation.watchPosition(watchPositionCallback);
}


/* HELPER FUNCTIONS AND CALLBACKS */

// callback for watchPosition() used to handle the returned position data
// as well as run searches
function watchPositionCallback(position){
  var pos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  }

  //new google maps LatLng object
  var currentLocation = new google.maps.LatLng(pos.lat, pos.lng);

  //update request object to be sent to nearBySearch()
  //with the currentLocation object as the specified location
  nearByChurchSearchRequest.location = currentLocation;
  nearByStoreSearchRequest.location = currentLocation;

  // center the map on the currentLocation object
  // and update userMarker position
  map.setCenter(currentLocation);
  userMarker.setPosition(currentLocation);

  console.log(userMarker.getPosition()); // returns _.E {}

  // initialize new PlacesServices
  placesChurchService = new google.maps.places.PlacesService(map);
  placesStoreService = new google.maps.places.PlacesService(map);

  // service methods used to search nearby queries based on the requests
  placesChurchService.nearbySearch(nearByChurchSearchRequest, searchCallback);
  placesStoreService.nearbySearch(nearByStoreSearchRequest, searchCallback);
}

PS:我也尝试过getCurrentLocation(),但这也没有任何改变。

【问题讨论】:

    标签: javascript google-maps geolocation


    【解决方案1】:

    调用 LatLong 对象上的方法

    您对 userMarker.getPosition() 的调用会返回一个 LatLng 对象。

    在此对象上使用 .lat() 和 .lng(),如下所示

    https://developers.google.com/maps/documentation/javascript/reference#LatLng

    var pos = userMarker.getPosition();
    console.log( pos.lat(), pos.lng() );

    【讨论】:

    • 我现在明白了。你必须调用方法来返回它,它不仅仅是静态的......谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2012-01-06
    • 2018-08-10
    • 2013-08-24
    • 2011-02-10
    相关资源
    最近更新 更多