reactjs中使用高德地圖計算兩個經緯度之間的距離


第一步下載依賴

npm install --save react-amap

第二步,在組件中使用

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Map, Marker } from 'react-amap';

export default class Page1 extends Component {
    
    constructor(){
        super();
        this.toolEvents = {
          created: (tool) => {
            this.tool = tool;
          }
        }
        this.mapPlugins = ['ToolBar'];
        this.mapCenter = {longitude: 120, latitude: 35};
        this.markerPosition = {longitude: 121, latitude: 36};
      }

    render () {
        return (
            <div style={{height:"100%"}}>
                <Map
                    version={'1.4.4'}//amap版本
                    amapkey={'注冊一個高德地圖應用的appkey'}
                    plugins={this.mapPlugins}
                    center={this.mapCenter}
                    zoom={6}
                    expandZoomRange={true}
                    zooms={10}
                    animateEnable={true}
                    useAMapUI>
                    <Marker position={this.markerPosition} />
                </Map>
            </div>
        )
    }
}

第三步,點擊地圖上的一點計算兩點之間的距離,添加events

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Map, Marker } from 'react-amap';

const events = { click: (e) => { var p1 = [116.434027, 39.941037]; var p2 = [e.lnglat.lng,e.lnglat.lat]; var dis=window.AMap.GeometryUtil.distance(p1, p2); console.log(dis) }, }

export default class Page1 extends Component {
    
    constructor(){
        super();
        this.toolEvents = {
          created: (tool) => {
            this.tool = tool;
          }
        }
        this.mapPlugins = ['ToolBar'];
        this.mapCenter = {longitude: 120, latitude: 35};
        this.markerPosition = {longitude: 121, latitude: 36};
      }

    render () {
        return (
            <div style={{height:"100%"}}>
                <Map
                    version={'1.4.4'}//amap版本
                    amapkey={'你注冊一個高德地圖應用的appkey'}
                    plugins={this.mapPlugins}
                    center={this.mapCenter}
                    zoom={6}
                    expandZoomRange={true}
                    zooms={10}
                    animateEnable={true}
                    events={events}
                    useAMapUI>
                    <Marker position={this.markerPosition} />
                </Map>
            </div>
        )
    }
}

最后效果圖如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM