城市列表(七)02-主页导航栏获取当前城市名称——百度地图地理定位基本用法

主页导航栏获取城市名称

  • 获取当前城市名称
    • H5引入的地理定位API
    • 基于IP地址进行定位
    • 基于WiFi也可以进行定位
    • 基于GPS方式进行定位
// 获取当前城市
getCurrentCity = () => {
  const position = new window.BMap.LocalCity()
  position.get((ret) => {
    let cname = ret.name
    console.log(cname)
  })
}
const res = await axios.get(`http://localhost:8080/area/info`, {
  params: {
    name: cityName
  }
})
window.localStorage.setItem('hkzf_city', JSON.stringify(res.data.body))
实例-百度地图地理定位用法

第一步:打开百度地图开放平台,找到JavaScript API v3.0下的定位功能,选择IP定位示例

地址:http://lbsyun.baidu.com/index.php?title=jspopular3.0/guide/geolocation

官网示例

var map = new BMap.Map("allmap");
var point = new BMap.Point(116.331398,39.897445);
map.centerAndZoom(point,12);

function myFun(result){
	var cityName = result.name;
	map.setCenter(cityName);
	alert("当前定位城市:"+cityName);
}
var myCity = new BMap.LocalCity();
myCity.get(myFun);

第二步:在当前界面src/views/Index/index.js首页中,react生命周期componentDidMount里进行操作

页面代码

        {/* 顶部导航栏 */}
        <NavBar
          mode="dark"
          leftContent={this.state.currentCity}
          onLeftClick={() => {
            // 点击时跳转到选择城市的页面
            this.props.history.push('/city')
          }}
          rightContent={[
            <Icon onClick={() => {console.log('right')}} key="0" type="search" style={{ marginRight: '16px' }} />
          ]}
        >首页</NavBar>

示例

import React from 'react'
import axios from 'axios'

class Test extends React.Component {
  componentDidMount() {
console.log("aaa")
    // 通过百度地图的地理定位API获取当前城市信息
    let myCity = new window.BMap.LocalCity();
    myCity.get(async (result) => {
      console.log(result);
      console.log(result.name);
      // 获取到定位的城市名称后需要进行缓存
      let currentCity = await axios('area/info', {
        params: {
          name: result.name
        }
      })
      console.log(currentCity);
      // 获取城市详细信息后,缓存起来
      localStorage.setItem('currentCity', JSON.stringify(currentCity.body))
    })
  }
  render () {
    return (
      <div  style={{width: '100%', height: '667px'}}>
      </div>
    )
  }
}

export default Test

现用

  componentDidMount () {
    this.loadSwiper()
    this.loadGroups()
    this.loadNews()
    // 从本地缓存获取城市名称
    let city = localStorage.getItem('currentCity')
    console.log(city)
    city = JSON.parse(city)//转义成标准字符串
    // 更新状态
    this.setState({
      currentCity: city.label
    })
    // 通过百度地图的地理定位API获取当前城市信息
    let myCity = new window.BMap.LocalCity();
    myCity.get(async (result) => {
      //console.log(result);
         //console.log(result.name);
      // 获取到定位的城市名称后需要进行缓存
      let currentCity = await axios('area/info', {
        params: {
          name: result.name
        }
      })
      //console.log(currentCity);
      // 获取城市详细信息后,缓存起来
      localStorage.setItem('currentCity', JSON.stringify(currentCity.body))
    })
  }

打印result

在这里插入图片描述

打印定位城市信息-currentCity

在这里插入图片描述

最终效果-当前定位城市

在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐