首页 > 解决方案 > 如何放大距离标记15公里范围内的区域

问题描述

我正面临一个问题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);
<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>

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

标签: javascriptjqueryleafletmaps

解决方案


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

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

简而言之:构建一个以 Marker 为中心、半径为 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());

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

现在,如果您希望在更改标记位置时发生这种情况,则只需在每次移动时重复该过程。就像您重复使用标记一样,您也可以重复使用虚拟 Circle,因为它具有相同的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);

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

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


推荐阅读