如何在按下按钮后重新居中Mapbox JS?

3

使用 Google Maps API 在按下按钮后重新将地图居中到新城市是非常简单的,但是我需要为项目使用来自 MapBox 的自定义地图。不幸的是,他们的文档并没有提供帮助。

var map;
function initialize() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: new google.maps.LatLng(48.1293954,11.556663), // Munich Germany
    zoom: 10
  });
}

function newLocation(newLat,newLng) {
 map.setCenter({
  lat : newLat,
  lng : newLng
 });
}

google.maps.event.addDomListener(window, 'load', initialize);
    </script>
 <script>
$(document).ready(function () {
     $("#1").on('click', function () {
   newLocation(48.1293954,11.556663);
 });
  $("#2").on('click', function () {
   newLocation(40.7033127,-73.979681);
 });
   $("#3").on('click', function () {
   newLocation(55.749792,37.632495);
 });
});

这段代码来自另一篇文章:如何通过点击按钮更改Google地图中心 我的问题是如何使用mapbox.js和leaflet api实现这个功能?我尝试过的所有方法都失败了。
2个回答

0
实际上,我已经弄清楚了。您可以使用Leaflet的L.LatLng来为坐标添加新的操作符号。而是.setView()方法让我感到困惑。

var map;

function initialize() {
    var coordinates = new L.LatLng(40.673859, -73.970114);
    map = new L.mapbox.map('map')
        .setView(coordinates, 12)
        .addLayer(L.mapbox.tileLayer('myMapID'));
  
}

function newLocation(newLat,newLng,newZoom) {
    var newCoord = new L.LatLng(newLat,newLng)
    map.setView(newCoord, newZoom);
}
  
window.addEventListener('load',initialize,false);


$(document).ready(function() {
    $("#1").on('click', function () {
        newLocation(40.765172,-73.978844,12);
    });
    $("#2").on('click', function () {
        newLocation(35,-75,4);
    });
    $("#3").on('click', function () {
        newLocation(15,-75,4);
    });

});

  


-1

我认为你应该进行修改:

map.setCenter({
    lat : newLat,
    lng : newLng
});

to:

map.setCenter(new google.maps.LatLng(newLat, newLng));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接