0

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

这是我的代码:

<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 米的半径范围内。我必须如何修改我的脚本才能让它检查数组中的所有位置?

非常感谢帮助!

4

1 回答 1

0

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

例如,这是一个演示,它利用鼠标跟随的标记来模拟 GeolocationMarker 的实例。请注意,对于此示例,radiusInMeters 设置为 100 米,以使演示更易于执行,并且演示还仅对用户尚未“访问”的标记起作用。

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

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

希望您可以看到如何在其中合并 GeolocationMarker 而不是 mousemove 东西,基本上只需要添加 GeolocationMarker 脚本,删除地图上 mousemove 的事件侦听器,创建 GeolocationMarker 而不是此处使用的 Marker,然后取消注释地图。在 position_changed 事件处理程序中调用 setCenter(userPosition)。哦,把 radiusInMeters 改回 10

于 2013-11-03T10:33:17.267 回答