2016-04-22 56 views
-1

我正在使用小册子在地图上进行实时用户跟踪。我画出了这个圈子作为所有用户的边界。如果用户超出边界,我需要提醒消息。我正在跟踪用户。只有我需要警告用户的消息不在边界。小册子实时出现圆圈边界警报

var shipLayer = L.layerGroup(); 
var ships = L.icon({ 
    iconUrl: 'images/marker.png', 
    iconSize: [16, 20] 
}); 
var popup; 
var region; 
var fen = { 
    lat: "17.4468", 
    lng: "78.3922" 
}; 
var i = 1; 
var realtime = L.realtime(

    function(success, error) { 
    var ship = mockShip(); 
    success(ship); 
    }, { 
    interval: refresh * 1000, 
    getFeatureId: function(featureData) { 
     return featureData.properties.userName; 
    }, 
    pointToLayer: function(feature, latlng) { 
     region = ''; 
     if (typeof ship === "undefined" || ship === null) { 
     var title = feature.properties.userName + " - " + feature.properties.gpsTime; 
     popup = L.popup() 
      .setLatLng(latlng) 
      .setContent(feature.properties.userName + '<br/>' + feature.properties.gpsTime + '<br/>BatteryInfo:' + feature.properties.batteryInfo + '%') 
      .openOn(map); 
     marker = L.marker(latlng, { 
      title: title, 
      icon: ships 
     }); 
     // this is my code for alert 
     if (fen.lat < feature.properties.latitude && fen.lng < feature.properties.longitude) { 
      alert('hi'); 
     } 
     //end 
     region = L.circle(fen, 450, { 
      color: 'red', 
      fillColor: '#f03', 
      fillOpacity: 0 
     }).addTo(map); 
     marker.bindPopup(popup); 
     marker.on('mouseover', function(e) { 
      this.openPopup(); 
     }); 
     marker.on('mouseout', function(e) { 
      this.closePopup(); 
     }); 
     marker.addTo(shipLayer); 
     return marker; 
     } 
    } 
    }).addTo(map); 

回答

0

你可以用turf.js做到这一点很容易地:

marker = L.marker(latlng, { 
    title: title, 
    icon: ships 
}); 
region = L.circle(fen, 450, { 
    color: 'red', 
    fillColor: '#f03', 
    fillOpacity: 0 
}).addTo(map); 
if (turf.distance(marker.toGeoJSON(), region.toGeoJSON()) * 1000 > 450) { 
    alert('You are outside the circle!'); 
} 

turf.distance将返回两个GeoJSON的点之间的距离。结果在这里乘以1000,因为L.circle使用米作为半径,而turf.distance默认为公里。这是表示该工作简单小提琴:

http://jsfiddle.net/nathansnider/nv2tL6mz/

当你点击圆外,警报将被触发。

+1

FYI:不需要像草坪此额外的LIB拉,因为'L.LatLng'对象都有一个'distanceTo'方法。因此,我的回答;) – iH8

+0

啊,那更好! – nathansnider

2

可以使用的L.LatLngdistanceTo方法来计算两个坐标之间的距离:

返回使用半正矢公式计算出的距离(以米为单位),以给定的经纬度。

http://leafletjs.com/reference.html#latlng-distanceto

// Get L.LatLng object of the circle 
var circleLatLng = circle.getLatLng(); 

// Get L.LatLng object of the marker 
var markerLatLng = marker.getLatLng(); 

// Calculate distance: 
var distance = circleLatLng.distanceTo(markerLatLng); 

// Use distance in a condition: 
if (distance > 450) { 
    // Out of bounds, do stuff 
}