您的位置:首页 > Web前端 > JavaScript

JS使用google地图API完成一个完整地图应用

2013-10-23 17:07 513 查看
注意:

1.这是一个完整应用,分别实现了定位、添加标记、标记点开窗口、watchme和clearme实现及时跟踪开关、移动显示路径功能

2.关于js的地图API, geolocation最重要的是getCurrentPosition方法, 其余两个为watchPosition(即时跟踪),clearWatch(取消即时跟踪)



                                                                                    

3.google地图API的使用方法,一般就是先定义对象,对象里有一些google定义的固定属性,然后将该对象传入google的构造函数里

4.说说第三个参数 positionOptions,它的选项和默认值为

var positionOptions = 

{

enableHighAccuracy:false,     //是否允许高精度定位,启动的话会耗电很大但是会确定的相对准确,否则如果只想知道用户大概位置就没必要打开

timeout:infinty,  //超时处理,默认是无限大也就是没有处理,如果在指定时间(毫秒)内不能确定一个位置,就会调用错误程序

maximumAge:0  //报告当前位置的年龄,如果当前位置持续时间超过了设置时间,就会尝试获取新位置,否则就返回缓存已有对象

}

代码部分:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>google地图</title>

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>   //google地图api地址
<script>

// BEGIN
// 计算两点距离成品代码,在起点的经度,纬度和终点的经度,纬度之间
//
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 = 6371; // radius of the Earth in km
var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) +
Math.cos(startLatRads) * Math.cos(destLatRads) *
Math.cos(startLongRads - destLongRads)) * Radius;

return distance;
}

function degreesToRadians(degrees) {
radians = (degrees * Math.PI)/180;
return radians;
}
// END

var map = null;    //map地图全局变量,包含我们所创建的google地图
var watchId = null;      //跟踪的wathId
var prevCoords = null;  //前一坐标,用于显示路径

var options =
{
enableHighAccuracy:true,
timeout:100,
maximumAge:0
}

function getMyLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(displayLocation, displayError, options);
var watchButton = document.getElementById("watch");
watchButton.onclick = watchLocation;  //即时定位的函数
var clearButton = document.getElementById("clearWatch");
clearButton.onclick = clearWatch;  //取消即时定位的函数

}
else
{
alert ("oops, no geolocation support");
}
}

function watchLocation()
{
watchId = navigator.geolocation.watchPosition(displayLocation, displayError);  //使用watchPosition进行跟踪,返回一个watchId,可以用它来取消跟踪
}

function clearWatch()
{
navigator.geolocation.clearWatch(watchId);  //根据watchId取消跟踪
watchId = null;
}

function scrollMapToPosition(coords)
{
var latitude = coords.latitude;
var longitude = coords.longitude;
var latlong = new google.maps.LatLng(latitude, longitude);
map.panTo(latlong);  //绘制路径,取这个latlong对象并滚动地图,是你最新位置处于中心点
addMarker(map, latlong, "Your new location", "You moved to:" + latitude + "," + longitude);
}

function displayError(error)    //error对象有一个code属性,其中包含一个0-3的数。这是用js为各个错误码关联一个错误消息的好方法。
{
var errorTypes =   //我们创建的错误消息对象,包括4个属性
{
0:"Unknow error",
1:"Permission denied by user",
2:"Position is not available",
3:"Request timed out"
};
var errorMessage = errorTypes[error.code];   //将错误对象和error.code进行关联,并赋值给errorMessage
if (error.code == 0 || error.code == 2)
{
errorMessage = errorMessage + "" + error.message;  //对于错误0和2,有时候error.message会有一些额外信息,所以增加进去
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;

options.timeout += 100;
navigator.geolocation.getCurrentPosition(displayLocation, displayError, options);
div.innerHTML += ".....checking again with timeout=" + options.timeout;
}

function displayLocation(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
var distance = document.getElementById("distance");
var km = computeDistance(position.coords, ourCoords);  //起点和终点计算距离
div.innerHTML = "You are at Latitude" + latitude + ", longitude" + longitude;
distance.innerHTML = "You are " + km + "km from the wickedlySmart HQ"
div.innerHTML += "(with" + position.coords.accuracy + "meters accuracy)";    //accuracy确定精度,单位为米,越小越精确,越大越不精确
div.innerHTML += "(found in " + options.timeout + "milliseconds)";
if (map == null)
{
showMap(position.coords);
prevCoords = position.coords;  //当前坐标赋值给前一坐标变量
}
else
{
var meters = computeDistance(position.coords, prevCoords) * 1000;
if (meters > 20)  //如果前一坐标和现在坐标差距大于20
{
scrollMapToPosition(position.coords);
prevCoords = position.coords;
}

}
}

var ourCoords =           //这是Wickedlysmart总部的位置,用于显示你和他的距离
{
latitude:47.624851,
longitude:-122.52099
}

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);
}
);
}

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);
}

window.onload = getMyLocation;
</script>

<link rel="stylesheet" href="../HFhtml5/chapter5/myLoc.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">
</div>
<div id="map">
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐