javascript - 使用 Google Maps API JS 访问标记和地点的位置

标签 javascript google-maps geolocation

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

基本上,我正在为位于 map 中心位置的用户创建一个标记。然后我正在运行 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()这也不会改变任何事情。

最佳答案

调用 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() );

关于javascript - 使用 Google Maps API JS 访问标记和地点的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645249/

相关文章:

java - Android 版 Google map 未呈现

java - 如何根据以纬度和经度为界的形状确定面积?

javascript - 有没有办法识别在谷歌地图中拖动了哪个指针

google-maps - 使用 TypeScript 在 React 中延迟加载 Google Maps 库

android - Android 网络位置提供商的准确度和速度有多快?

javascript - 地理定位方法查看用户是否在特定区域

javascript - CSS 挫折 : How to center floating images of different widths inside LI tags?

javascript - 管理轮播指示器的宽度

javascript - 手机上的剩余悬停效果

javascript - 如何使用 Angular 2/4 的鼠标滚轮事件测试指令