You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React中如何获取经纬度?使用geolocation API仅返回纬度经度为null怎么办

问题原因

核心是经度字段拼写不一致:

  • 初始化state时你把经度字段名错写为longitutde(多了一个字母t)
  • getCoordinates方法中setState更新的是正确拼写的longitude字段,相当于给state新增了一个未被渲染的字段
  • 页面渲染时读取的还是初始定义的拼写错误的longitutde字段,该字段从未被更新,所以始终为null

修复方案

统一所有位置的经度字段拼写为正确的longitude即可,修复后代码示例:

constructor(props) {
  super(props);
  this.state = {
    latitude: null,
    longitude: null,
  };
  this.getLocation = this.getLocation.bind(this);
  this.getCoordinates = this.getCoordinates.bind(this);
}

getLocation(){
  navigator.geolocation.getCurrentPosition(this.getCoordinates, this.handleLocationError);     
}

getCoordinates(position){
  this.setState({ 
    latitude: position.coords.latitude, 
    longitude: position.coords.longitude
  })
} 

<Button onClick={this.getLocation} className="mt-1 loc-button" variant="outline-info" >Get current location</Button>
<p>Latitude: {this.state.latitude}</p>
<p>Longitude: {this.state.longitude}</p>

补充注意

如果修改拼写后仍有定位问题,可以检查以下两点:

  • 浏览器是否开启了当前页面的定位权限
  • 页面是否运行在HTTPS环境或者localhost本地环境,目前大部分浏览器的Geolocation API不支持非加密的公网HTTP环境

内容的提问来源于stack exchange,提问作者rin ichinose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:36:04