我在访问标记和地点的地理位置时遇到问题。
基本上,我正在为位于 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/