在react+ts项目中安装leaflet
参考文档 1.安装leaflet:
npm install leaflet --save
2.安装**@types/leaflet**( 如果不是typescript项目则安装react-leaflet)
npm install -D @types/leaflet 3.初次使用:
import React, { Component } from 'react'
import L from 'leaflet'
import './Fristmap.css'
export default class Firstmap extends Component {
componentDidMount(){
const mymap = L.map('firstmap').setView([51.505, -0.09], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'your.mapbox.access.token'
}).addTo(mymap);
}
render() {
return (
<div id='firstmap' >
</div>
)
}
}
效果:报错了 查看官网文档:
在使用前需要先有一个access token,可以注册一个mapbox账号获取对应token,注册账号的地址再官网中。注册好后可以看到一个默认的公共的token
使用这个token
和预期结果不太一样,而且无法准确缩放: 原因:没有引入css: 在index.html中加入:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
或者将css文件下载到本地后引入。 最终效果:
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lingliu0824/article/details/112689510