Leaflet.js 将地图集中在一组标记上 [英] Leaflet.js center the map on a group of markers

查看:15
本文介绍了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.

我知道谷歌地图有自动居中功能,但我将如何使用 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 对象数组即可.例如:

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天全站免登陆