react+leaflet入门Demo


1 代码架构

使用create-react-app脚手架创建react工程
这里写图片描述

2 引用leaflet的js和css文件

在Index.html中引用上述文件

  • css文件
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css"
   integrity="sha512-wcw6ts8Anuw10Mzh9Ytw4pylW8+NAD4ch3lqm9lzAsTxg0GFeJgoAtxuCLREZSC5lUXdVyo/7yfsqFjQ4S+aKw=="
   crossorigin=""/>
  • js文件
<script src="https://unpkg.com/leaflet@1.1.0/dist/leaflet.js"
  integrity="sha512-mNqn2Wg7tSToJhvHcqfzLMU6J4mkOImSPTxVZAdo+lcPlk+GhZmYgACEe0x35K7YzW1zJ7XyJV/TT1MrdXvMcA=="
  crossorigin=""></script>

3 编写map组件

在componentDidMount()中加载地图

import L from 'leaflet'
import React  , { Component} from 'react'

class MapIndex extends Component{
    componentDidMount()
    {
        var mymap = L.map('root').setView([51.505,-0.09],13);
        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: 18
        }).addTo(mymap);
    }
  render()
  {
    return( //这里(不能写到下一行,否则react认为render中没有返回任何内容
      <div> </div>
    )
  }
}
export default MapIndex

4 在index.js中加载MapIndex组件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import MapIndex from './components/MapIndex'
ReactDOM.render(<MapIndex />, document.getElementById('root'));

5 在index.js对应的css中指定地图容器div的高度样式

#root { height: 100vh; }

上述步骤完成后,执行
npm start
地图正确加载
这里写图片描述

转载自:https://blog.csdn.net/naipeng/article/details/76595440

You may also like...