在react中使用leaflet

 

如果有样式问题,检查是否引入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);
}

移动地图

设置中心点,setView()
center接受数组和对象,数组两个长度,第一个是lat,第二个lng, 对象 {lat:20,lng:150}
zoom为数字,缩放数值
this.map.setView(
center,zoom
)

posted @ 2019-10-11 10:19  RoseTying  阅读(2031)  评论(0编辑  收藏  举报