如果有样式问题,检查是否引入leaflet.css,地图容器是否标注宽高

引入方式:

import React from 'react';
import L from 'leaflet';

class Map extends React.Component {
  componentDidMount() {
    // create map
    this.map = L.map('map', {
      center: [49.8419, 24.0315],
      zoom: 16,
      layers: [
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
          attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }),
      ]
    });
  }

  render() {
    return <div id="map"></div>
  }
}

export default Map;



添加标记
componentDidMount() {
  ...
  // add marker
  this.marker = L.marker(this.props.markerPosition).addTo(this.map);
}



更新标记
componentDidUpdate({ markerPosition }) {
  // check if position has changed
  if (this.props.markerPosition !== markerPosition) {
    this.marker.setLatLng(this.props.markerPosition);
  }
}

添加标记层
componentDidMount() {
  ...
  // add layer
  this.layer = L.layerGroup().addTo(this.map);
}



02-11 03:01