• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LDLX@Y火星
博客园    首页    新随笔    联系   管理    订阅  订阅

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>
        )
    }
}

最后效果图如下

 

posted @ 2018-11-27 01:21  火星黑洞  阅读(2491)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3