需求:对用户输入的地址在高德地图上进行定位显示
运用技术栈:React+TS
请求方式:axios
操作平台:Web
地址转经纬度
1. 封装
/**
* 将地址转换为经纬度
* @param address : 地址
* @base 高德api
* @return: 经度和维度
*/
addressToLocation = (address: any) => {
return new Promise((resolve, reject) => {
// 这个key是我个人的key用于作为参数进行调用高德api等一系列高德操作 这里只是拿我个人的作为示范
//你们可以自己去申请属于自己的key,最好不用我得了, 如果你们不知道不知道如何申请key可以百度或者问我都可以
const key = '70790502eb5fb33b2c8c031b8b65de82'
const base = `http://restapi.amap.com/v3/geocode/geo?key=${key}&address=${address}`
const err = '没有匹配到地点'
axios.get(base).then(({ data }) => {
const { geocodes } = data
const { location } = geocodes[0]
const longitudeAndLatitude = location.split(',')
if (data.info === 'OK') resolve({ code: 200, longitude: longitudeAndLatitude[0], latitude: longitudeAndLatitude[1] })
else reject(err)
})
})
}
2. 调用
this.addressToLocation(address).then((res) => {
const { longitude, latitude } = res
this.setState({
markerPosition: { longitude, latitude } // 注意markerPosition即为地图上面显示的点
})
})
3. 定义基础属性和数据
constructor (props: SelectSiteProps) {
super(props)
this.mapPlugins = ['ToolBar']
this.mapCenter = { longitude: 120, latitude: 35 }
this.events = {
created: (ins: any) => { console.log(ins) },
// 点击地图上的点会触发此函数此函数会携带你所点击点的所有信息
click: (e:any) => {
const { lnglat: { lat, lng } } = e
this.setState({ markerPosition: { longitude: lng, latitude: lat } })
}
}
this.state = {
markerPosition: { longitude: 121, latitude: 36 }
}
}
如果在React+TS中使用还需1添加类型定义(在constructor上面添加即可)
tool: any
mapPlugins: any[]
mapCenter: { longitude: number; latitude: number }
events: { created: (ins: any) => void; click: (e:any) => void }
属性说明(附贴上高德官方地址更多属性说明请移至此处https://elemefe.github.io/react-amap/components/map#)
![](https://img.haomeiwen.com/i17010818/a685c5ab9b92822b.png)
![](https://img.haomeiwen.com/i17010818/41a39e0a139452d0.png)
经纬度转地址
addressToLocation = (location: any) => {
return new Promise((resolve, reject) => {
const key = '70790502eb5fb33b2c8c031b8b65de82'
const base = `http://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${location}`
axios.get(base).then(({ data }) => {
console.log(data) // data里面会有转换好的地区等信息
})
}
道理同以上地址转经纬度一致 所以在此不过多说明
网友评论