如何缩放标记周围 15 公里半径范围内的区域

2 javascript maps jquery leaflet

我遇到了一个问题leaflet map。他们是

  1. 我在移动标记时无法缩放 15km radius(从)marker

  2. 我无法在移动时画线(不是优先事项

这是我尝试过的

请参考 jsfiddle,因为代码片段不起作用

jsfiddle: http: //jsfiddle.net/eabangalore/x4gokvoa/8/

// Create the map
var map = L.map('map').setView([-31.4, -64.183], 12);

// Set up the OSM layer
L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18
}).addTo(map);

// add a marker in the given location
var lat = -31.4;
var lng = -64.183;
var marker = L.marker([lat, lng]).addTo(map);

// add a layer and add points
var myLayer = L.geoJson().addTo(map);

// geojsonFeature
var geojsonFeature = {
    "type": "Feature",
        "properties": {
        "name": "Coors Field",
            "amenity": "Baseball Stadium",
            "popupContent": "This is where the Rockies play!"
    },
        "geometry": {
        "type": "Point",
            "coordinates": [-104.99404, 39.75621]
    }
};

// put the marker
setTimeout(function () {
    myLayer.addData(geojsonFeature);
}, 1000);

// update the marker
setTimeout(function () {
    // clear layer
    myLayer.clearLayers(); // inherited from LayerGroup
    //myLayer.addData(geojsonFeature);
}, 3000);

// put the marker
setTimeout(function () {
    myLayer.addData(geojsonFeature);
}, 5000);

// just fooling around
setInterval(function () {
    lat = lat + ((Math.random() * 1) - 0.25) * 0.001;
    lng = lng + ((Math.random() * 1) - 0.5) * 0.001;
    marker.setLatLng([lat, lng]).update();
}, 200);
Run Code Online (Sandbox Code Playgroud)
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<link href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" rel="stylesheet"/>
<div id="map"></div>
Run Code Online (Sandbox Code Playgroud)

请帮助我提前谢谢!!!!

ghy*_*ybs 6

如果您想让地图“缩放”(实际上是fitBounds)到您的标记位置并显示其周围 15 公里半径区域,您可以简单地使用此答案的变体:

给定中心和正方形宽度的传单正方形

简而言之:构建一个以标记为中心、半径为 15,000 米的“虚拟”getBounds,使用其方法检索其边界并将其提供给地图的fitBounds方法:

var marker = L.marker(myLatLng).addTo(map);
var radius = 15000; // in meters.
var circle = L.circle(myLatLng, radius).addTo(map);

map.fitBounds(circle.getBounds());
Run Code Online (Sandbox Code Playgroud)

注意:您不必将圆圈添加到地图中,即使未显示它也可以工作。

现在,如果您希望每当更改标记的位置时都会发生这种情况,则只需在每次移动时重复该过程即可。就像重新使用标记一样,您也可以重新使用虚拟圆,因为它具有相同的setLatLng方法:

setInterval(function() {
  lat = lat + ((Math.random() * 1) - 0.25) * 0.001;
  lng = lng + ((Math.random() * 1) - 0.5) * 0.001;
  var newLatLng = [lat, lng];
  marker.setLatLng(newLatLng).update();
  circle.setLatLng(newLatLng);
  map.fitBounds(circle.getBounds());
}, 200);
Run Code Online (Sandbox Code Playgroud)

更新了 JSFiddle: https: //jsfiddle.net/x4gokvoa/9/

注意:将您的 JSFiddle 更新到 Leaflet 版本 0.7.7。您应该尝试更新到版本 1+。当前版本是1.3.1