基于标记的中心传单地图

时间:2018-10-12 11:22:18

标签: html leaflet

这是我的新手,但是找不到解决我问题的有效方法。 我想根据标记将地图居中。我发现了很多示例,但没有成功。

有人可以帮我吗?

var startmarkers = [
  ['Paris', 48.8581817, 2.3454923, 0, './Paris/index.html', 'France'],
  ['London', 51.5097076, -0.1327514, 1, './London/index.html', 'UK'],
  ['Amsterdam', 52.3723963, 4.8954506, 2, './Amsterdam/index.html', 'Netherlands'],
  ['Brussels', 50.8455315, 4.3554069, 3, './Brussels/index.html', 'Belgium'],
];

var map = L.map('map').setView([49.2595092, 3.5204334], 6);
//var map = L.map('map').fitBounds(startmarkers.getBounds()); --- Not Working ---

mapLink =
  '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
  'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; ' + mapLink + ' Contributors',
    maxZoom: 18,
  }).addTo(map);

for (var i = 0; i < startmarkers.length; i++) {
  marker = new L.marker([startmarkers[i][1], startmarkers[i][2]])
    .bindPopup('<a href=\"' + startmarkers[i][4] + '\">' + startmarkers[i][0] + '<br>' + startmarkers[i][5])
    .addTo(map);
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"></script>

<div id="map" style="width: 1024px; height: 600px"></div>

1 个答案:

答案 0 :(得分:0)

您需要有一个仅包含各个数组(arrayOfLatLngs数组)内每个标记的坐标的数组。 之后,创建一个边界并传递L.LatLngs数组 并最终拟合地图上的边界:

var map = L.map('map').setView([49.2595092, 3.5204334], 6);

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 startmarkers = [
  ['Paris', 48.8581817, 2.3454923, 0, './Paris/index.html', 'France'],
  ['London', 51.5097076, -0.1327514, 1, './London/index.html', 'UK'],
  ['Amsterdam', 52.3723963, 4.8954506, 2, './Amsterdam/index.html', 'Netherlands'],
  ['Brussels', 50.8455315, 4.3554069, 3, './Brussels/index.html', 'Belgium'],
];



mapLink =
  '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
  'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; ' + mapLink + ' Contributors',
    maxZoom: 18,
  }).addTo(map);

let arrayOfMarkers = [];
for (let i = 0; i < startmarkers.length; i++) {
  marker = new L.marker([startmarkers[i][1], startmarkers[i][2]])
    .bindPopup('<a href=\"' + startmarkers[i][4] + '\">' + startmarkers[i][0] + '<br>' + startmarkers[i][5])
    .addTo(map);

  arrayOfMarkers.push([startmarkers[i][1], startmarkers[i][2]])
}
console.log(arrayOfMarkers)

/* var arrayOfMarkers = [
  [48.8581817, 2.3454923],
  [51.5097076, -0.1327514],
  [52.3723963, 4.8954506],
  [50.8455315, 4.3554069],
] */
var bounds = new L.LatLngBounds(arrayOfMarkers);
map.fitBounds(bounds);
<link href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" rel="stylesheet"/>
<script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js"></script>
<div id="map" style="width: 600px; height: 600px"></div>