React使用高德地图 (高德地图原生)(二)

本文介绍如何在React应用中直接使用高德地图原生API,而非依赖react-amap库。通过在HTML文件中引入地图插件,然后在React组件中利用ref获取元素并在componentDidMount()中初始化地图。地图加载后,可以参照高德API进行进一步操作,如地图标记等。代码实现可直接复制使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

React使用高德地图,之前介绍的方法是使用react-amap基于React进行封装的地图组件。除了使用这种方法,我们也可以直接使用高德原生的方法进行操作。

地图插件引入

首先script引入这个就不多说了,在项目的html文件里

    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.3&key="你自己的key"&plugin=AMap.Autocomplete,AMap.PlaceSearch,AMap.Geocoder"></script>

用到的一下插件、组件什么的,和react-amap使用的方式保持一致。再有不明白的,可以直接去官网与看:https://lbs.amap.com/api/javascript-api/summary

React中的使用

			<div>
			//地图容器外层需要再多一层
				<div style={
   
   {
   
   width:650,height:255}} ref="container">
        			  </div>
			</div> 

上 面加载地图容器在react使用的是ref,这样我们在componentDidMount()这个生命周期里,就可以去获取到这个元素,并进行地图的初始化操作

componentDidMount() {
   
   
      const _this = this
      let content = this.refs.container
      let content1 = '<div>定位中....</div>'
      let map = new window.AMap.Map(content,{
   
   
          resizeEnable:true,
          zoom:15
      })
 }

地图初始化加载出来后,剩余的一些操作可以参照官网给的API进行处理。我这边也是针对react-amap实现的功能利用高德原生API重新写了一边,代码如下:

import React, {
   
   Component} from 'react'
import marker from 'SRC/statics/images/signin/marker2.png'
import classname from 'classnames'
import styles from './index.scss'
import {
   
    message } from 'antd'

class MapDetail extends Component {
   
   
  constructor (props) {
   
   
      super (props)
      this.state = {
   
   
          searchContent:'',
      }
  }

  placeSearch = (e) => {
   
   
      this.setState({
   
   searchContent:e})
  }

  searchPlace = (e) => {
   
   
      console.log(1234,e)
  }




  componentDidMount() {
   
   
      const _this = this
      let content = this.refs.container
      let content1 = '<div>定位中....</div>'
      let map = new window.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值