如果用户关闭并触发特定事件,请检查位置数组 [英] Check array of locations if user is close and trigger specific event

查看:87
本文介绍了如果用户关闭并触发特定事件,请检查位置数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我成功地确定用户是否在单个标记的某个距离内。
接下来我想做的是检查脚本,如果用户接近存储在数组中的多个位置之一。如果是的话,我想让脚本触发相应位置的特定事件。



这是我的代码:

 < script type =text / javascriptsrc =https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true> ;< /脚本> 
< script>
var map,GeoMarker;

函数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);

//标记

var locations = [
['1',49.463344,11.079942,6],
['2',49.462309,
['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 (位置[i] [1],位置[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); //需要是一个变量!

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达到了?
var JustEnteredRadius =!IsWithinRadius&& IsCurrentPositionInRadius ; //半径到达!
IsWithinRadius = IsCurrentPositionInRadius;

if(JustEnteredRadius){
//触发事件
}
}
} );

GeoMarker.setMap(map);
}
google.maps.event.addDomListener(window,'load',initialize);
< / script>

正如您所看到的,我有一个脚本来检查用户是否在10米范围内围绕特定的坐标。 我该如何修改脚本才能检查数组中的所有位置?

非常感谢!当您创建标记时,可以将它们存储在一个数组中,或者将每个位置转换为该标记,并将位置数据存储在数组中标记它是自己的。然后你需要一个函数来遍历该数组,并检查并存储每个标记与用户的距离,将每个标记放入一个新的数组中以供临时使用。然后按距离用户的距离对新数组中的标记进行排序,然后从该数组中移除任何大于用户最大距离的标记。一旦你有了这个数组,如果有剩下的东西,你就知道第一个项目是最接近的标记。您可以根据您当前处理的标记来确定您希望发生什么事件。

例如,下面是一个演示,其中使用了跟随您的标记鼠标来模拟GeolocationMarker的一个实例。请注意,对于此示例,radiusInMeters设置为100米,以使演示更容易启动,演示也仅对尚未被用户访问的标记起作用。

 <!DOCTYPE html> 
< html>
< head>
< meta http-equiv =content-typecontent =text / html; charset = utf-8>
< title>标记寻宝< / title>
< script src =https://maps.googleapis.com/maps/api/js?v=3.exp&library=geometry&sensor=false>< / script>
< / head>
< body>
< div id =map_canvasstyle =width:500px; height:400px; margin:0 auto;>< / div>
< div id =UserCoordinatesstyle =text-align:center;>将鼠标悬停在地图上并靠近标记< / div>
< script>

函数initialize(){
var i,marker,GeoMarker,
gm = google.maps,
mapOptions = {
panControl:false,
mapTypeControl:false,
streetViewControl:false,
overviewMapControl:false,
disableDoubleClickZoom:false,
滚轮:false,
zoom:17,
center:new google.maps.LatLng(49.452,11.077),
mapTypeId:google.maps.MapTypeId.ROADMAP
},
map = new gm.Map(document.getElementById(' map_canvas'),mapOptions),
locations = [
['Treasure 1',49.463344,11.079942,6],
['Treasure 2',49.462309,11.078335,4],
['Treasure 3',49.463466,11.084214,5],
['Treasure 4',49.46348,11.076061,3],
['Treasure 5',49.464345,11.07885,2],
['宝藏6', 49.461095,11.079601,1]
],
infowindow = new gm.InfoWindow(),
markersVisited = 0,
bounds = new gm.LatLngBounds(),
GeoMarker = new gm.Marker({
position:new gm.LatLng(100,0),
icon:'http://maps.google.com/mapfiles/kml/pal3/icon20.png '
});
gm.event.addListener(map,'mousemove',function(evt){
GeoMarker.setPosition(evt.latLng);
});
for(i = 0; i< locations.length; i ++){
latLng = new gm.LatLng(locations [i] [1],locations [i] [2]);
bounds.extend(latLng);
marker = new gm.Marker({
position:latLng,
map:地图,
图标:'http://google.com/mapfiles/kml/paddle/' +(i + 1)+' - lv.png',
index:i,
title:locations [i] [0],
data:locations [i] [3],
visited:false
});
gm.event.addListener(marker,'click',function(){
infowindow.setContent(this.title);
infowindow.open(map,this);
});
locations [i] = marker;
}
map.fitBounds(bounds);
函数getClosestMarkers(userPosition,maxDistance){
var i,marker,mPos,
len = locations.length,
arr = [];
//为所有标记赋值distanceFromUser
(i = 0; i< len; i ++){
marker = locations [i];
mPos = marker.getPosition();
marker.distanceFromUser = gm.geometry.spherical.computeDistanceBetween(userPosition,mPos);
//忽略已被访问过的标记,如果他们
//尚未被访问,则将它们存储在arr
中if(!marker.visited){
arr.push(marker);


//通过distanceFromUser排列arr中的项目,最接近最远的
arr.sort(函数(m1,m2){
var a = m1。 distanceFromUser,
b = m2.distanceFromUser;
if(a == b){
return 0;
}
return(a> b)?1: - 1;
});
//从arr中删除大于maxPistance的所有标记,这些标记远离userPosition
for(i = arr.length - 1; i> = 0; i--){
marker = ARR [I];
if(marker.distanceFromUser> maxDistance){
arr.pop();
}
}
return arr;
}
gm.event.addListener(
GeoMarker,$ b $'position_changed',
function(){
var marker,closestMarkers,
radiusInMeters = 100,
userPosition = this.getPosition(),
displayElement = document.getElementById('UserCoordinates');
if(userPosition === null){
return;
}
//仅在GeoocationMarker的实际GeoMarker实例
//map.setCenter(userPosition);
nearestMarkers = getClosestMarkers(userPosition,radiusInMeters);
if(markersVisited == locations.length){
displayElement.innerHTML ='已找到所有标记';
} else if(closestMarkers.length){
// here你会决定触发什么事件,
//基于哪个ma rker closestMarkers [0]是
//location.replace(\"puzzle.php);
marker = closestMarkers [0];
displayElement.innerHTML = marker.title;
displayElement.innerHTML + =',marker.data ='+ marker.data +',marker.index ='+ marker.index;
marker.visited = true;
markersVisited ++;
}
}
);
GeoMarker.setMap(map);
}
google.maps.event.addDomListener(window,'load',initialize);

< / script>
< / body>
< / html>

示例小提琴: http://jsfiddle.net/uXpGD/



希望您可以看到如何将GeolocationMarker而不是鼠标移动到那里,基本上会只需添加GeolocationMarker脚本,移除鼠标移动到地图上的事件侦听器,创建GeolocationMarker而不是此处使用的Marker,并取消position_changed事件处理程序中的map.setCenter(userPosition)调用的注释。哦,并将radiusInMeters改回10


I succeeded to determine if the user is within a certain distance of a single marker. What I want to do next is to have the script check, if the user is close to one of multiple locations stored in an array. If yes, I want to have the script trigger the event specific to the respective location.

Here is my code:

<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>

As you can see, I have a script that checks if the user is within a radius of 10 meters around a specific coordinate. How do I have to modify my script in order to have it check for all the locations in the array?

Help greatly appreciated!

解决方案

When you create the markers, either store them in an array or just convert each location to that marker and store the locations data within the marker it's self. Then you need a function to loop through that array and check and store each markers distance from the user, placing each marker into a new array for temporary use. Then sort the markers in that new array by distance from user, then remove any markers from that array which are greater than max distance from user. Once you have this array, if there's anything left in it you know that the first item is the closest marker. You determine what 'event' you wish to have happen based upon which marker you are currently dealing with.

For example, here is a demo which utilizes a marker that follows your mouse to simulate an instance of GeolocationMarker. Note that for this example the radiusInMeters is set to 100 meters to make the demo simpler to actuate, and the demo also only acts upon markers which have not yet been 'visited' by the user.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Markers Treasure Hunt</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=false"></script>
</head>
<body>
<div id="map_canvas" style="width:500px; height:400px; margin:0 auto;"></div>
<div id="UserCoordinates" style="text-align:center;">Mouse over the map and go close to the markers</div>
<script>

function initialize() {
    var i, marker, GeoMarker,
        gm = google.maps,
        mapOptions = {
            panControl: false,
            mapTypeControl: false,
            streetViewControl: false,
            overviewMapControl: false,
            disableDoubleClickZoom: false,
            scrollwheel: false,
            zoom: 17,
            center: new google.maps.LatLng(49.452, 11.077),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        map = new gm.Map(document.getElementById('map_canvas'), mapOptions),
        locations = [
            ['Treasure 1', 49.463344, 11.079942, 6],
            ['Treasure 2', 49.462309, 11.078335, 4],
            ['Treasure 3', 49.463466, 11.084214, 5],
            ['Treasure 4', 49.46348, 11.076061, 3],
            ['Treasure 5', 49.464345, 11.07885, 2],
            ['Treasure 6', 49.461095, 11.079601, 1]
        ],
        infowindow = new gm.InfoWindow(),
        markersVisited = 0,
        bounds = new gm.LatLngBounds(),
        GeoMarker = new gm.Marker({
            position: new gm.LatLng(100, 0),
            icon: 'http://maps.google.com/mapfiles/kml/pal3/icon20.png'
    });
    gm.event.addListener(map, 'mousemove', function (evt) {
        GeoMarker.setPosition(evt.latLng);
    });
    for (i = 0; i < locations.length; i++) {
        latLng = new gm.LatLng(locations[i][1], locations[i][2]);
        bounds.extend(latLng);
        marker = new gm.Marker({
            position: latLng,
            map: map,
            icon: 'http://google.com/mapfiles/kml/paddle/'+ (i + 1) +'-lv.png',
            index: i,
            title: locations[i][0],
            data: locations[i][3],
            visited: false
        });
        gm.event.addListener(marker, 'click', function () {
            infowindow.setContent(this.title);
            infowindow.open(map, this);
        });
        locations[i] = marker;
    }
    map.fitBounds(bounds);
    function getClosestMarkers(userPosition, maxDistance) {
        var i, marker, mPos,
            len = locations.length,
            arr = [];
         //assign distanceFromUser for all markers
        for (i = 0; i < len; i++) {
            marker = locations[i];
            mPos = marker.getPosition();
            marker.distanceFromUser = gm.geometry.spherical.computeDistanceBetween(userPosition, mPos);
             //ignoring markers which have been 'visited' already, if they
             //have not yet been 'visited', store them in arr
            if (!marker.visited) {
                arr.push(marker);
            }
        }
         //arrange items in arr by distanceFromUser, closest to furthest
        arr.sort(function (m1, m2) {
            var a = m1.distanceFromUser,
                b = m2.distanceFromUser;
            if (a == b) {
                return 0;
            }
            return (a > b) ? 1 : -1;
        });
         //remove all markers from arr which are greater than maxDistance away from userPosition
        for (i = arr.length - 1; i >= 0; i--) {
            marker = arr[i];
            if (marker.distanceFromUser > maxDistance) {
                arr.pop();
            }
        }
        return arr;
    }
    gm.event.addListener(
        GeoMarker,
        'position_changed',
        function () {
            var marker, closestMarkers,
                radiusInMeters = 100,
                userPosition = this.getPosition(),
                displayElement = document.getElementById('UserCoordinates');
            if (userPosition === null) {
                return;
            }
            //only use the below line with your actual GeoMarker instance of GeolocationMarker
            //map.setCenter(userPosition);
            closestMarkers = getClosestMarkers(userPosition, radiusInMeters);
            if (markersVisited == locations.length) {
                displayElement.innerHTML = 'All markers already found';
            } else if (closestMarkers.length) {
                //here is where you would determine what event to trigger,
                //based upon which marker closestMarkers[0] is
                //location.replace("puzzle.php");
                marker = closestMarkers[0];
                displayElement.innerHTML = marker.title;
                displayElement.innerHTML += ', marker.data = '+ marker.data +', marker.index = '+ marker.index;
                marker.visited = true;
                markersVisited++;
            }
        }
    );
    GeoMarker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);

</script>
</body>
</html>

Example fiddle: http://jsfiddle.net/uXpGD/

Hopefully you can see how to incorporate GeolocationMarker instead of the mousemove stuff there, basically would just need to add the GeolocationMarker script, remove the event listener for mousemove over the map, create your GeolocationMarker instead of the Marker used here, and uncomment the map.setCenter(userPosition) call in the position_changed event handler. Oh, and change the radiusInMeters back to 10

这篇关于如果用户关闭并触发特定事件,请检查位置数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆