Home  >  Article  >  Web Front-end  >  js method code for obtaining GPS coordinates

js method code for obtaining GPS coordinates

不言
不言Original
2018-08-15 17:49:333241browse

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

Get the cursor/mouse with js in the page The coordinates and the pixel coordinates of the cursor_javascript skills

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn