美文网首页
使用javaScript API实现地理定位

使用javaScript API实现地理定位

作者: 淘码小工 | 来源:发表于2017-09-08 17:02 被阅读79次
1. 使用地理定位确定位置
  • IP地址定位
  • CPS定位
  • 蜂窝电话基站定位
  • wifi定位

一个聪明的浏览器可能会首先使用蜂窝电话三角定位,如果这个方法可行,你会得到一个大致的位置,然后使用Wi-Fi或GPS提供一个更精确的位置。

2.使用javascrip API实现定位
  1. 首先创建location.html页面
<!DOCTYPE html>
<html>
<head>
    <title>Where am I ?</title>
    <meta charset="utf-8">
    <script src = "myLoc.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>  
    <link type="text/css" rel="stylesheet" href="js.css">
</head>
<body>
    <form>
        <input type="button" id="watch" value="Watch me">
        <input type="button" id="clearWatch" value="Clear watch">
    </form>
    <div id="location">
        Your location will go here.
    </div>
    <div id="distance">
    Distance from WickedlySmart HQ will go here.
    </div>
    <div id="map">
       
    </div>
</body>
</html>
  1. 使用javascrip API 的getCurrentPosition方法获取经纬度和错误值。
//location.js
var options = {
    enableHighAccuracy:true,  //是否启动高精度,启用后会很费电
    timeout:100,     //timeout 会控制浏览器确定位置的时间,默认是毫秒。
    maximumAge: 0    //这个值是保存缓存的时间,如果在时间之内请求定位,会用缓存的值,如果超过时间,请求现在的位置信息
};

window.onload = function() {
    if(navigator.geolocation) {   //查看是否支持定位,如果不支持,则navigator.geolocation返回null
        navigator.geolocation.getCurrentPosition(displayLocation, displayError, options);  //getCurrentPosition有三个参数 1.successHanlder 2.errorHanlder 3.options,这里我们只输入了successHandler 后两个是可选的
        // var watchButton = document.getElementById("watch");
        // watchButton.onclick = watchLocation;
        // var clearWatchButton = document.getElementById("clearWatch");
        // clearWatchButton.onclick = clearWatch;
    } else {
        alert("Oops, no geolocation support");
    }
}

//successHandler
function displayLocation (position){  //position是地理定位API向它传入一个position对象,其中包含有关浏览器位置的信息
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var div = document.getElementById("location");
    div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
    div.innerHTML += " (fonud in " + options.timeout + "milliseconse)";  //浏览器成功得到你的位置时,我们会让用户知道花了多长时间
}

function displayError(error) {
    var errorTypes = {  //error对象有一个code属性,其中包含一个0-3的数
        0: "Unknown error",
        1: "Permission denied by user",
        2: "Position is not available",
        3: "Request timed out"
    };

    var errorMessage = errorTypes[error.code];
    if(error.code == 0 || error.code == 2) {
        errorMessage = errorMessage + " " + error.message;
    }

    var div = document.getElementById("location");
    div.innerHTML = errorMessage;

    //如果第一次定位失败,我们会把titmeout时间增加100ms,然后再试
    options.timeout += 100;
    navigator.geolocation.getCurrentPosition(
        displayLocation,
        displayError,
        options
        );
    div.innerHTML += "........ checking again with timeout=" +  options.timeout;
}

getCurrentPosition有三个参数

  • displayLocation是一个函数,如果浏览器能成功确定你的位置,则会调用这个函数,并且会传一个position的对象,这个对象包含两个两个属性coords和timestamp。
    coords中又包含 latitude, longitude,accuracy这几个属性,还有其他属性在这里就不写了。

  • 另外两个属性是可选的。displayError是第二个函数,当获取定位信息失败时,会在函数内部传入一个错误的对象。

  • 第三个参数是positionOptions参数。利用这个参数,可以控制地理定位如何计算他的值。

3. 利用两个坐标值来获取距离
//回去两个坐标值的距离
function computeDistance(startCoords, destCoords) {
    var startLatRads = degreesToRadians(startCoords.latitude);
    var startLongRads = degreesToRadians(startCoords.longitude);
    var destLatRads = degreesToRadians(destCoords.latitude);
    var destLongRads = degreesToRadians(destCoords.longitude);

    var Radius = 7371;  //radius of the Earth in km
    var distance = (Math.sin(startLatRads) * Math.sin(destLatRads) + 
        Math.cos(startLatRads) * Math.cos(destLatRads) * 
        Math.cos(startLongRads - destLongRads)) * Radius;

    return distance;
}

//把经纬度转化为度数
function degreesToRadians(degrees) {
    var radians = (degrees * Math.PI)/180;
    return radians;
}
4.把地图添加到浏览器网页中
// //谷歌地图
var map = null;

function showMap(coords)  
{  
    var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);  //googlemaps API所有方法前面都有google.maps,并且构造函数注意大写,LatLng                                                                                                                                                                 取我们的经度和纬度  
    var mapOptions = {  
        zoom:10,    //可以指定0-21的值,数值越大越显示更多细节,10大概是城市规模  
        center:googleLatAndLong,    //中心点  
        mapTypeId:google.maps.MapTypeId.ROADMAP   //还有SATELLITE和HYBIRD  
    };  
    var mapDiv = document.getElementById("map");  
    map = new google.maps.Map(mapDiv, mapOptions);   //全局map在这里使用
}
5.在地图中添加大头针
//在地图上添加大头针
function addMarker (map, latlong, title, content)  //添加标记的函数,参数分别是,地图,经纬,窗口标题和窗口内容  
{  
    var markerOptions =    //定义对象,属性为google固定指定的  
    {  
        position:latlong,     
        map:map,  
        title:title,  
        clickable:true  
    };  
    var marker = new google.maps.Marker(markerOptions);  //google的标记构造函数  
      
    var infoWindowOptions =  //弹出窗口设置  
    {  
        content:content,  
        position:latlong  
    };  
    var infoWindow = new google.maps.InfoWindow(infoWindowOptions);  
      
    google.maps.event.addListener(marker, "click", function ()  //google.maps.event.addListener为点击事件增加监听者,监听者就像一个处理程序,类似onclick onload  
    {  
        infoWindow.open(map);  
    });  
}  
6.实时监控
//实时监控
var watchId = null;
function watchLocation() {
    watchId = navigator.geolocation.watchPosition(displayLocation, displayError);
}

function clearWatch() {
    if(watchId) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
    }
}

//记录路径
function scrollMapToPosition(coords) {
    var latitude = coords.latitude;
    var longitude = coords.longitude;
    var latlong = new google.maps.LatLng(latlong, longitude);

    map.panTo(latlong);  //地图的panTo方法取这个LagLng对象并滚动地图,是你的新位置位于地图中心
    addMarker(map, latlong, "Your new location", "you moved to: " + latitude + ", " + longitude);

}

全部代码如下
myLoc.js

var options = {
    enableHighAccuracy:true,  //是否启动高精度,启用后会很费电
    timeout:100,     //timeout 会控制浏览器确定位置的时间,默认是毫秒。
    maximumAge: 0    //这个值是保存缓存的时间,如果在时间之内请求定位,会用缓存的值,如果超过时间,请求现在的位置信息
};
window.onload = function() {
    if(navigator.geolocation) {   //查看是否支持定位,如果不支持,则navigator.geolocation返回null
        navigator.geolocation.getCurrentPosition(displayLocation, displayError, options);  //getCurrentPosition有三个参数 1.successHanlder 2.errorHanlder 3.options,这里我们只输入了successHandler 后两个是可选的
        // var watchButton = document.getElementById("watch");
        // watchButton.onclick = watchLocation;
        // var clearWatchButton = document.getElementById("clearWatch");
        // clearWatchButton.onclick = clearWatch;
    } else {
        alert("Oops, no geolocation support");
    }
}

//successHandler
function displayLocation (position){  //position是地理定位API向它传入一个position对象,其中包含有关浏览器位置的信息
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var div = document.getElementById("location");
    div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
    // div.innerHTML += " (with " + position.coords.accuracy + " meters accuracy)";  //这里用到position的accuracy属性,并追加到<div>的innerHTML的末尾
    div.innerHTML += " (fonud in " + options.timeout + "milliseconse)";  //浏览器成功得到你的位置时,我们会让用户知道花了多长时间

    var km = computeDistance(position.coords, ourCoords);
    var distance = document.getElementById("distance");
    distance.innerHTML = "You are " + km + " km from the WickedlySmart HQ";

    if(map == null){
       showMap(position.coords);
    }else {
        scrollMapToPosition(position.coords)
    }
}

function displayError(error) {
    var errorTypes = {  //error对象有一个code属性,其中包含一个0-3的数
        0: "Unknown error",
        1: "Permission denied by user",
        2: "Position is not available",
        3: "Request timed out"
    };

    var errorMessage = errorTypes[error.code];
    if(error.code == 0 || error.code == 2) {
        errorMessage = errorMessage + " " + error.message;
    }

    var div = document.getElementById("location");
    div.innerHTML = errorMessage;

    //如果第一次定位失败,我们会把titmeout时间增加100ms,然后再试
    options.timeout += 100;
    navigator.geolocation.getCurrentPosition(
        displayLocation,
        displayError,
        options
        );
    div.innerHTML += "........ checking again with timeout=" + options.timeout;
}

//回去两个坐标值的距离
function computeDistance(startCoords, destCoords) {
    var startLatRads = degreesToRadians(startCoords.latitude);
    var startLongRads = degreesToRadians(startCoords.longitude);
    var destLatRads = degreesToRadians(destCoords.latitude);
    var destLongRads = degreesToRadians(destCoords.longitude);

    var Radius = 7371;  //radius of the Earth in km
    var distance = (Math.sin(startLatRads) * Math.sin(destLatRads) + 
        Math.cos(startLatRads) * Math.cos(destLatRads) * 
        Math.cos(startLongRads - destLongRads)) * Radius;

    return distance;
}

//把经纬度转化为度数
function degreesToRadians(degrees) {
    var radians = (degrees * Math.PI)/180;
    return radians;
}

var ourCoords = {
    latitude: 47.624851,
    longitude: -122.52099
};


// //谷歌地图
var map = null;

function showMap(coords)  
{  
    var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);  //googlemaps API所有方法前面都有google.maps,并且构造函数注意大写,LatLng                                                                                                                                                                 取我们的经度和纬度  
    var mapOptions = {  
        zoom:10,    //可以指定0-21的值,数值越大越显示更多细节,10大概是城市规模  
        center:googleLatAndLong,    //中心点  
        mapTypeId:google.maps.MapTypeId.ROADMAP   //还有SATELLITE和HYBIRD  
    };  
    var mapDiv = document.getElementById("map");  
    map = new google.maps.Map(mapDiv, mapOptions);   //全局map在这里使用  


    var title = "Your Location";  
    var content = "You are here" + coords.latitude + coords.longitude;  
    addMarker(map, googleLatAndLong, title, content); 
}

//在地图上添加大头针
function addMarker (map, latlong, title, content)  //添加标记的函数,参数分别是,地图,经纬,窗口标题和窗口内容  
{  
    var markerOptions =    //定义对象,属性为google固定指定的  
    {  
        position:latlong,     
        map:map,  
        title:title,  
        clickable:true  
    };  
    var marker = new google.maps.Marker(markerOptions);  //google的标记构造函数  
      
    var infoWindowOptions =  //弹出窗口设置  
    {  
        content:content,  
        position:latlong  
    };  
    var infoWindow = new google.maps.InfoWindow(infoWindowOptions);  
      
    google.maps.event.addListener(marker, "click", function ()  //google.maps.event.addListener为点击事件增加监听者,监听者就像一个处理程序,类似onclick onload  
    {  
        infoWindow.open(map);  
    });  
}  


//实时监控
var watchId = null;
function watchLocation() {
    watchId = navigator.geolocation.watchPosition(displayLocation, displayError);
}

function clearWatch() {
    if(watchId) {
        navigator.geolocation.clearWatch(watchId);
        watchId = null;
    }
}

//记录路径
function scrollMapToPosition(coords) {
    var latitude = coords.latitude;
    var longitude = coords.longitude;
    var latlong = new google.maps.LatLng(latlong, longitude);

    map.panTo(latlong);  //地图的panTo方法取这个LagLng对象并滚动地图,是你的新位置位于地图中心
    addMarker(map, latlong, "Your new location", "you moved to: " + latitude + ", " + longitude);

}

js.css

#map {
    width:400px;
    height: 400px;
    margin: 10px;
    background-color: #444432;
}

#distance {
    color: blue;
}



知行办公,专业移动办公平台https://zx.naton.cn/
【总监】十二春秋之,3483099@qq.com
【Master】zelo,616701261@qq.com
【运营】运维艄公,897221533@qq.com;****
【产品设计】流浪猫,364994559@qq.com
【体验设计】兜兜,2435632247@qq.com
【iOS】淘码小工,492395860@qq.comiMcG33K,imcg33k@gmail.com
【Android】人猿居士,1059604515@qq.com;思路的顿悟,1217022114@qq.com
【java】首席工程师MR_W,feixue300@qq.com
【测试】土镜问道,847071279@qq.com
【数据】fox009521,42151960@qq.com
【安全】保密,你懂的。

相关文章

  • 使用javaScript API实现地理定位

    1. 使用地理定位确定位置 IP地址定位 CPS定位 蜂窝电话基站定位 wifi定位 一个聪明的浏览器可能会首先使...

  • 踩坑之地理定位2

    我之前讲了如何能够使用地理定位,按照之前的介绍,我们可以开始使用百度、高德的Api来进行地理定位,我这边要实现的是...

  • HTML5获取地理位置信息Geolocation API

    地理定位是HTML5中新增的API特性,它允许JavaScript程序向浏览器询问用户真实的地理位置。 方法: n...

  • 使用echarts结合百度地图API做迁徙图

    echarts.js原先可以不使用百度地图API,直接实现迁徙图的效果。后来因为一些原因,地理信息的定位需要借助百...

  • iOS 后台定位

    后台定位实现步骤:(涉及类CLLocationManager) 1.使用API:-requestAlwaysAut...

  • js地理位置api(调用百度地图API)

    1. JS地理位置api介绍 2. JS具体实现 3. 使用百度地图 1. JS地理位置api介绍 navigat...

  • iOS百度地图使用时的注意问题

    iOS使用百度地图时会发现,API本身不带定位功能的,定位是通过iOS系统自身的定位实现的,百度地图API只是封装...

  • 地图(一)之CoreLocation

    CoreLocation CoreLocation用于地理定位,地理编码区域监听等(着重功能实现) 1.获取定位授...

  • 8.25兄弟会

    js调用百度地图api实现定位 百度地图的API,接口很丰富,实现定位功能 // 百度地图API功能 varmap...

  • 对 'CoreLocation' say so

    应用场景 定位 地图CoreLocation : 用于地理定位, 地理编码, 区域监听等(着重功能实现)MapKi...

网友评论

      本文标题:使用javaScript API实现地理定位

      本文链接:https://www.haomeiwen.com/subject/qdhnjxtx.html