我成功地确定了用户是否在单个标记的一定距离内。我接下来要做的是让脚本检查,如果用户靠近存储在数组中的多个位置之一。如果是,我想让脚本触发特定于相应位置的事件。
这是我的代码:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true"></script>
<script>
var map, GeoMarker;
function initialize() {
var mapOptions = {
panControl: false,
mapTypeControl: false,
streetViewControl: false,
overviewMapControl: false,
disableDoubleClickZoom: false,
scrollwheel: false,
zoom: 17,
center: new google.maps.LatLng(99.000, 10.000),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// Markers
var locations = [
['1', 49.463344,11.079942, 6],
['2', 49.462309,11.078335, 4],
['3', 49.463466,11.084214, 5],
['4', 49.46348,11.076061, 3],
['5', 49.464345,11.07885, 2],
['6', 49.461095,11.079601, 1]
];
var infowindow = new google.maps.InfoWindow();
var mark1, i;
for (i = 0; i < locations.length; i++) {
mark1 = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(mark1, 'click', (function(mark1, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, mark1);
}
})(mark1, i));
}
GeoMarker = new GeolocationMarker();
var IsWithinRadius = false;
var RadiusInMeters = 10;
var LocationOfInterest = new google.maps.LatLng(49.463344,11.079942); // Needs to be a variable!
google.maps.event.addListener(GeoMarker, 'position_changed', function() {map.setCenter(this.getPosition());
var UserPosition = this.getPosition();
var DisplayElement = document.getElementById('UserCoordinates');
if(UserPosition === null) {IsWithinRadius = false;}
var IsCurrentPositionInRadius =
Math.abs(google.maps.geometry.spherical.computeDistanceBetween(UserPosition, LocationOfInterest)) <= RadiusInMeters; // Radius reached?
var JustEnteredRadius = !IsWithinRadius && IsCurrentPositionInRadius; // Radius reached!
IsWithinRadius = IsCurrentPositionInRadius;
if(JustEnteredRadius) {
// Trigger Event
}
}
});
GeoMarker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
如您所见,我有一个脚本可以检查用户是否在特定坐标周围 10 米的半径范围内。我必须如何修改我的脚本才能让它检查数组中的所有位置?
非常感谢帮助!