mapboxgl,turf安装
npm install turf
npm install --save mapbox-gl
mapboxgl,turf引入
import turf from 'turf/turf'
import 'mapbox-gl/dist/mapbox-gl.css'
import mapboxgl from 'mapbox-gl';
townData格式
var townData = {
type:'FeatureCollection',
features:[
{
'type': 'Polygon',
'coordinates':[[[117.26,27.34],[117.26,27.38]...]]
},
{
'type': 'Polygon',
'coordinates':[[[117.26,27.34],[117.26,27.38]...]]
},
{
'type': 'Polygon',
'coordinates':[[[117.26,27.34],[117.26,27.38]...]]
}....
]
}
地图创建
<div id="map"></div>
this.mapbox = new mapboxgl.Map({
container: 'map',
style: {
"version": 8,
"glyphs": "./static/lib/mapbox-gl-js/fonts/{fontstack}/{range}.pbf",
"sources": {
"geoq.tile": {
"type": "raster",
"tiles": [
`${process.env.VUE_APP_MAPURL}/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}`
],
"tileSize": 256
}
},
"layers": [{
"id": "geoq",
"type": "raster",
"source": "geoq.tile"
}]
},
center: [this.longitude,this.latitude],
zoom: this.zoom,
pitch: 30,
bearing: 0
});
this.mapbox.on('load', ()=>{
this.addLabelLayer('town-label', this.townData);
})
添加label方法
addLabelLayer(id, data){
var newData = {
type:'FeatureCollection',
features:[]
}
data.features.forEach(feature=>{
var centroidPt = turf.centroid(feature)
centroidPt.properties = feature.properties
newData.features.push(centroidPt)
})
if(this.mapbox.getLayer(id)){
this.mapbox.removeLayer(id);
}
this.mapbox.addSource(id, {
'type': 'geojson',
'data': newData
});
this.mapbox.addLayer({
id: id,
type: "symbol",
source: id,
layout: {
"text-field": ["get", "NAME"],
"text-variable-anchor": ["top", "bottom", "left", "right"],
"text-radial-offset": 0.5,
"text-justify": "auto",
// "icon-image": image
},
paint: {
'text-color': '#ff0'
}
});
},
添加鼠标移入移出弹窗,注:'symbols'为icon图标id和source
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
this.mapbox.on('mouseenter', 'symbols', (e)=> {
debugger
const features = this.mapbox.queryRenderedFeatures(e.point);
if(features.length){
this.mapbox.getCanvas().style.cursor = 'pointer';
var coordinates = e.features[0].geometry.coordinates.slice()
var popupName = e.features[0].properties.name
var popupvalue = e.features[0].properties.value
const contain = `
<div class="popupClass">
<div class="popupClass-title">
<span>名称:</span>
<span>${popupName}</span>
</div>
<div class="popupClass-title">
<span>值:</span>
<span>${popupvalue}</span></div>
</div>
`
popup.setLngLat(coordinates)
.setHTML(contain)
.addTo(this.mapbox);
}
})
this.mapbox.on('mouseleave', 'symbols', (e)=> {
this.mapbox.getCanvas().style.cursor = '';
popup.remove();
})