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
地图正确加载
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值