Home >Web Front-end >JS Tutorial >How to use JS to get local latitude and longitude
The content of this article is to use js to obtain the local longitude and latitude. Friends in need can refer to
The simplest calling method
window.navigator.geolocation.getCurrentPosition(function (position) { console.log(position.coords.latitude) console.log(position.coords.longitude) })
The encapsulated code is as follows:
function getPosition () { return new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { let latitude = position.coords.latitude let longitude = position.coords.longitude let data = { latitude: latitude, longitude: longitude } resolve(data) }, function () { reject(arguments) }) } else { reject('你的浏览器不支持当前地理位置信息获取') } }) }
The calling method is as follows:
// 获取当前经纬度坐标 getPosition().then(result => { // 返回结果示例: // {latitude: 30.318030999999998, longitude: 120.05561639999999} // 一般小数点后只取六位,所以用以下代码搞定 let queryData = { longtitude: String(result.longitude).match(/\d+\.\d{0,6}/)[0], latitude: String(result.latitude).match(/\d+\.\d{0,6}/)[0], channelType: '00' } console.log(queryData) // 以下放置获取坐标后你要执行的代码: // ... }).catch(err => { console.log(err) })
Remember, this is an asynchronous operation, so the code that needs to be executed after obtaining the coordinates cannot be written directly after the function, but should be written in then (refer to The location written in the comment)
Related recommendations:
How to get the longitude and latitude through WeChat js
The above is the detailed content of How to use JS to get local latitude and longitude. For more information, please follow other related articles on the PHP Chinese website!