The content of this article is about the method code of js to obtain GPS coordinates. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
No more nonsense, let’s go straight to the code
1. This is relatively simple
function getLocation(){ if(navigator.geolocation){ //判断是否有这个对象 navigator.geolocation.getCurrentPosition(function(pos){ console.log("经度:"+pos.coords.longitude+ "纬度:"+pos.coords.latitude) }) }else{ console.log("当前系统不支持GPS API") } }
2. It’s more comprehensive. In fact, it’s not necessary. It depends on the individual. Like it
function getLocation(){ var options={ enableHighAccuracy:true, maximumAge:1000 } if(navigator.geolocation){ //浏览器支持geolocation // alert("浏览器支持geolocation"); navigator.geolocation.getCurrentPosition(onSuccess,onError,options); }else{ //浏览器不支持geolocation alert("浏览器不支持geolocation"); } }
When the acquisition is successful
function onSuccess(pos){ console.log("经度:"+pos.coords.longitude+ "纬度:"+pos.coords.latitude) }
When the acquisition fails, this error is deliberately written in detail to let you understand why it failed
function onError(error){ switch(error.code){ case 1: alert("位置服务被拒绝"); break; case 2: alert("暂时获取不到位置信息"); break; case 3: alert("获取信息超时"); break; case 4: alert("未知错误"); break; } }
Related recommendations:
PHP method to calculate the distance between two GPS coordinates on Baidu map, gps coordinates
The above is the detailed content of js method code for obtaining GPS coordinates. For more information, please follow other related articles on the PHP Chinese website!