【WebGIS实例】(4)Leaflet创建一个地图并加入定位功能

本文介绍了如何在Web应用中使用Leaflet库和Leaflet Locate Control插件来创建地图并实现定位功能。首先通过npm安装Leaflet及插件,接着创建一个地图类,设置地图的基本属性如缩放、中心点等,并添加OpenStreetMap作为底图。然后,添加定位控件到地图的右上角。最后,在HTML页面中加载地图,并提供了自定义定位方法的示例代码,包括处理定位成功和失败的回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、安装leaflet和leaflet的定位插件

npm install leaflet
npm install leaflet.locatecontrol

二、写一个地图类

import * as L from 'leaflet';
import 'leaflet.locatecontrol';

import 'leaflet/dist/leaflet.css';
import 'leaflet.locatecontrol/dist/L.Control.Locate.min.css';

class Map {
  map; // 地图对象

constructor() {
    this.map = L.map('map', { // 'map' 指的是挂载地图的div标签的ID
      minZoom: 2, // 最小缩放
      maxZoom: 24, // 最大缩放
      center: [23.125178, 113.280637], // 默认地图中心
      zoom: 6, // 默认缩放层级
      zoomControl: false, // 启用缩放控件

      attributionControl: false, // 禁用右下角的版权说明

      crs: L.CRS.EPSG3857,
    });
    // 添加底图
    L.tileLayer(
      'https://tile.openstreetmap.org/{z}/{x}/{y}.png', {},
    ).addTo(this.map);

    // 添加定位控件
    L.control
      .locate({
        position: 'topright', // 控件的位置
        showPopup: false, // 显示popup
      })
      .addTo(this.map);
  }
}

export default Map;

三、在页面上加载地图

在html页面上加个ID为’map’的标签:

  <div>
    <div id="map" />
  </div>

修改其的样式:

<style>
	#map {
		width: 100%;
		height: 100%;
	}
</style>

在js中,导入上面写的那个类,然后new一下就有地图了。


Leaflet.Locate 定位插件

Github地址:https://github.com/domoritz/leaflet-locatecontrol

可配置项参考:

OptionTypeDescriptionDefault
positionstringPosition of the controltopleft
layerILayerThe layer that the user’s location should be drawn on.a new layer
setViewboolean or stringSet the map view (zoom and pan) to the user’s location as it updates. Options are false, 'once', 'always', 'untilPan', or 'untilPanOrZoom''untilPanOrZoom'
flyTobooleanSmooth pan and zoom to the location of the marker. Only works in Leaflet 1.0+.false
keepCurrentZoomLevelbooleanOnly pan when setting the view.false
initialZoomLevelfalse or integerAfter activating the plugin by clicking on the icon, zoom to the selected zoom level, even when keepCurrentZoomLevel is true. Set to false to disable this feature.false
clickBehaviorobjectWhat to do when the user clicks on the control. Has three options inView, inViewNotFollowing and outOfView. Possible values are stop and setView, or the name of a behaviour to inherit from.{inView: 'stop', outOfView: 'setView', inViewNotFollowing: 'inView'}
returnToPrevBoundsbooleanIf set, save the map bounds just before centering to the user’s location. When control is disabled, set the view back to the bounds that were saved.false
cacheLocationbooleanKeep a cache of the location after the user deactivates the control. If set to false, the user has to wait until the locate API returns a new location before they see where they are again.true
showCompassbooleanShow the compass bearing on top of the location markertrue
drawCirclebooleanIf set, a circle that shows the location accuracy is drawn.true
drawMarkerbooleanIf set, the marker at the users’ location is drawn.true
markerClassclassThe class to be used to create the marker.LocationMarker
compassClassclassThe class to be used to create the marker.CompassMarker
circleStylePath optionsAccuracy circle style properties.see code
markerStylePath optionsInner marker style properties. Only works if your marker class supports setStyle.see code
compassStylePath optionsTriangle compass heading marker style properties. Only works if your marker class supports setStyle.see code
followCircleStylePath optionsChanges to the accuracy circle while following. Only need to provide changes.{}
followMarkerStylePath optionsChanges to the inner marker while following. Only need to provide changes.{}
followCompassStylePath optionsChanges to the compass marker while following. Only need to provide changes.{}
iconstringThe CSS class for the icon.leaflet-control-locate-location-arrow
iconLoadingstringThe CSS class for the icon while loading.leaflet-control-locate-spinner
iconElementTagstringThe element to be created for icons.span
circlePaddingarrayPadding around the accuracy circle.[0, 0]
createButtonCallbackfunctionThis callback can be used in case you would like to override button creation behavior.see code
getLocationBoundsfunctionThis callback can be used to override the viewport tracking behavior.see code
onLocationErrorfunctionThis even is called when the user’s location is outside the bounds set on the map.see code
onLocationOutsideMapBoundsfunctionUse metric units.see code
showPopupbooleanDisplay a pop-up when the user click on the inner marker.true
stringsobjectStrings used in the control. Options are title, text, metersUnit, feetUnit, popup and outsideMapBoundsMsgsee code
strings.popupstring or functionThe string shown as popup. May contain the placeholders {distance} and {unit}. If this option is specified as function, it will be executed with a single parameter {distance, unit} and expected to return a string.see code
locateOptionsLocate optionsThe default options passed to leaflets locate method.see code

如果要自己写一个定位方法

// 获取定位
// this.map是地图对象
getLocation() {
	this.map.locate({
		setView: true,
		// watch: true, // 持续监听位置
		// enableHighAccuracy: true, // 精准定位
	});
	
	// 'locationfound' 定位成功
	this.map.once('locationfound', (e) => {
		console.log(e)
	});
	// 'locationerror' 定位失败
	this.map.once('locationerror', (e) => {
	  console.log(e)
	});
}

然后将getLocation()这个方法绑定在按钮上,这样每次点击按钮就触发一次定位。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值