使用HTML5 geolocation 和 google Maps API

第一步,添加一个div标签,用来显示地图

<div ></div>

第二步,使用CSS使得地图显示更友好

<style>

#mapDiv {

width:500px;

height:300px;

border:1px solid #efefef;

margin:auto;

-moz-box-shadow:5px 5px 10px #000;

-webkit-box-shadow:5px 5px 10px #000;

}

</style>

第三步,添加google maps API

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

第四步,检查我们的地理位置,我们实际使用的浏览器

if(navigator.geolocation){

}

第五步,我们使用在HTML5 getCurrentPosition功能内置和传递函数称为hasPosition

navigator.geolocation.getCurrentPosition(hasPosition);

第六步,完成hasPosition函数

function hasPosition(position) {

var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude),

myOptions = {

zoom: 15,

center: point,

mapTypeId: google.maps.MapTypeId.ROADMAP

},

mapDiv = document.getElementById("mapDiv"),

map = new google.maps.Map(mapDiv, myOptions),

marker = new google.maps.Marker({

position: point,

map: map,

title: "You are here"

});

}

完整的代码如下

<!DOCTYPE html>

<html >

<head>

<meta charset="utf-8" />

<title>HTML5 Geolocation</title>

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

<script>

if(navigator.geolocation) {

function hasPosition(position) {

//创建一个变量,并传送经度和纬度到Google Maps获取你的地理位置

var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude),

//设置地图

myOptions = {

zoom: 15,

center: point,

mapTypeId: google.maps.MapTypeId.ROADMAP

},

//找到div标签把地图载入

mapDiv = document.getElementById("mapDiv"),

//传送div和地图设置到地图里

map = new google.maps.Map(mapDiv, myOptions),

marker = new google.maps.Marker({

position: point,

map: map,

title: "你在这里"

});

}

navigator.geolocation.getCurrentPosition(hasPosition);

}

</script>

<style>

#mapDiv {

width:500px;

height:300px;

border:1px solid #efefef;

margin:auto;

-moz-box-shadow:5px 5px 10px #000;

-webkit-box-shadow:5px 5px 10px #000;

}

</style>

</head>

<body>

<div ></div>

</body>

</html>