传单js地图不会在里面移动



我试图让地图在里面移动,把地图拖到一边,这样我就可以绕过地图了。

但这只可能是map1上的onmousedown,当选择map2时,地图不会移动,不可能拖动它。

当点击map1 button时,地图会出现,并且可以在其中移动,但当我点击map2 button后,就无法在地图中移动了。

遵循正在发生的事情的代码。

这怎么能解决?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
</head>
<body>
<div style="margin: 10px">
<button onclick="maps(['New York', 40.6971494, -74.2598757])">Map 1</button>
</div>
<div style="margin: 10px">
<button onclick="maps(['London', 51.528308, -0.3817849])">Map 2</button>
</div>
<div id="mapid" style="width: 200px; height: 200px; margin: 10px"></div>
<script>
function maps(location) {
var container = L.DomUtil.get('mapid');
if(container != null){
container._leaflet_id = null;
}
var map = L.map( 'mapid', {
center: [location[1], location[2]],
minZoom: 2,
zoom: 13
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var m = L.marker([location[1], location[2]]).addTo(map).bindPopup(location[0])
}
</script>
</body>
</html>

我发现了问题,我需要更改映射的初始化方式,按照下面的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>
</head>
<body>
<div style="margin: 10px">
<button onclick="maps(['New York', 40.6971494, -74.2598757])">Map 1</button>
</div>
<div style="margin: 10px">
<button onclick="maps(['London', 51.528308, -0.3817849])">Map 2</button>
</div>
<div id="mapid" style="width: 200px; height: 200px; margin: 10px"></div>
<script>
var map = null; //added
function maps(location) {

//var container = L.DomUtil.get('mapid'); //removed
//if(container != null){                  //removed
//    container._leaflet_id = null;       //removed
//}
if (map !== undefined && map !== null) { map.remove(); }//added
map = L.map( 'mapid', { //alterated
center: [location[1], location[2]],
minZoom: 2,
zoom: 13
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var m = L.marker([location[1], location[2]]).addTo(map).bindPopup(location[0])
}
</script>
</body>
</html>

最新更新