使用javaScript API实现地理定位

2017-09-08  本文已影响79人  淘码小工
1. 使用地理定位确定位置

一个聪明的浏览器可能会首先使用蜂窝电话三角定位,如果这个方法可行,你会得到一个大致的位置,然后使用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有三个参数

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
【安全】保密,你懂的。

上一篇下一篇

猜你喜欢

热点阅读