Leaflet.js将地图置于一组标记的中心 [英] Leaflet.js center the map on a group of markers

查看:463
本文介绍了Leaflet.js将地图置于一组标记的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Leaflet.js,并希望通过某种方式将地图放在我拥有的标记上居中,以便在页面启动时所有内容都位于用户视图内.如果所有标记都聚集在一个较小的区域中,那么我希望地图缩小到仍显示所有标记的级别.

I'm using Leaflet.js and would like some way to centre the map on the markers I have so that all are within the user's view when the page launches. If all the markers are clustered in a small area, I would like the map to zoom down to a level that still displays all of them.

我知道google maps具有自动居中功能,但是我如何用Leaflet.js做到这一点?

I know google maps has an auto-centre function but how would I go about this with Leaflet.js?

推荐答案

您可以使用 L.LatLngBounds 来创建一个要缩放的区域.

You can use L.LatLngBounds in order to create an area to zoom to.

首先,创建一个边界并将其传递给L.LatLngs数组:

First, create a bounds and pass it an array of L.LatLngs:

var bounds = new L.LatLngBounds(arrayOfLatLngs);

这将创建一个边界,该边界将封装数组中包含的每个点.有了边界后,就可以匹配地图的边界以匹配您创建的边界:

This will create a bounds that will encapsulate every point that is contained in the array. Once you have the bounds, you can fit the bounds of the map to match your created bound:

 map.fitBounds(bounds);

这将尽可能放大地图,同时仍包含数组中的每个点.

This will zoom the map in as far as it can go, while still containing every point in your array.

或者,您也可以通过简单地调用fitBounds方法并传入L.LatLng对象数组来调用fitBounds方法.例如:

Alternatively, you can also call the fitBounds method by simply calling it and passing in an array of L.LatLng objects. For example:

map.fitBounds([[1,1],[2,2],[3,3]]);

这将完全相同,而无需创建特定的L.LatLngBounds对象.

This would function exactly the same, without the need to create a specific L.LatLngBounds object.

这篇关于Leaflet.js将地图置于一组标记的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆