gpt4 book ai didi

javascript - 根据用户位置对谷歌地图中的标记进行排序

转载 作者:行者123 更新时间:2023-12-03 05:39:42 25 4
gpt4 key购买 nike

我有一个事件列表,在 map (其 Web 应用程序/网站)上显示为标记,我想仅显示距用户当前位置一定距离(10 公里)内的事件那么,我该如何结合这2个

//User Location
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function (position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
// alert ("Latitude"+currentLatitude+"Longitude"+currentLongitude);window.mapServiceProvider(position.coords.latitude,position.coords.longitude);
// console.log(position);
}

);
}


//List of location from the Db.
var markers = @Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//Set All merkers on the map
window.onload = function (a) {

var mapOptions = {
center: new window.google.maps.LatLng(window.markers[0].Latitude, window.markers[0].Longitude),
zoom: 12,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();


var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < window.markers.length; i++) {
var data = window.markers[i];

var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
// console.log(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function (marker, data) {
window.google.maps.event.addListener(marker,
"click",
function (e) {

infoWindow.setContent(data
.Venue +
" " +
data.Genre.Name +
" " +
data.DateTime.toString("dd/mm/yy"));
//.toISOString().split("T")[0]);
// .format('MM/DD h:mm');

infoWindow.open(map, marker);
});
})(marker, data);
};
};

最佳答案

您可以使用几何库来计算用户位置和标记之间的距离(以米为单位)。

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

过滤标记的代码快照可能类似于

var markers_filtered = markers.filter(function(marker, index, array) {
var myLatlng = new window.google.maps.LatLng(marker.Latitude, marker.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
for (var i = 0; i < markers_filtered.length; i++) {
//Your stuff here
}

加载 Maps JavaScript API 时,您应该添加libraries=geometry 参数。

https://developers.google.com/maps/documentation/javascript/geometry

关于javascript - 根据用户位置对谷歌地图中的标记进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com