yejinfu 2011-07-06
解析:
首先通过w3cGeolocation标准得到位置信息,此标准是html5的一部分。如果浏览器不支持w3cGeolocation标准,再通过googlegears软件得到位置信息,gears是一款支持离线工作的软件。
GoogleGears有几个主要的API组件:
一个本地服务器,用来存储和读取离线程序资源(包括HTML,JavaScript,images等)。
一个小型数据库(以SQLite构建),用来储存本地数据。
一个工作池,用来让开发者将本地数据与服务器端后台同步。
一个桌面模型可使网络程序的操作贴近桌面程序。
一个地理定位模型,能够让网络程序侦测到目前用户的地理位置。
源码:
<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="initial-scale=1.0,user-scalable=no"/>
<metahttp-equiv="content-type"content="text/html;charset=UTF-8"/>
<title>GoogleMapsJavaScriptAPIv3Example:MapGeolocation</title>
<linkhref="http://code.google.com/apis/maps/documentation/javascript/examples/default.css"rel="stylesheet"type="text/css"/>
<scripttype="text/javascript"src="http://maps.google.com/maps/api/js?sensor=true"></script>
<scripttype="text/javascript"src="http://code.google.com/apis/gears/gears_init.js"></script>
<scripttype="text/javascript">
varinitialLocation;
varsiberia=newgoogle.maps.LatLng(60,105);
varnewyork=newgoogle.maps.LatLng(40.69847032728747,-73.9514422416687);
varbrowserSupportFlag=newBoolean();
varmap;
varinfowindow=newgoogle.maps.InfoWindow();
functioninitialize(){
varmyOptions={
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=newgoogle.maps.Map(document.getElementById("map_canvas"),myOptions);
//TryW3CGeolocationmethod(Preferred)
if(navigator.geolocation){
browserSupportFlag=true;
navigator.geolocation.getCurrentPosition(function(position){
initialLocation=newgoogle.maps.LatLng(position.coords.latitude,position.coords.longitude);
contentString="LocationfoundusingW3Cstandard";
map.setCenter(initialLocation);
infowindow.setContent(contentString);
infowindow.setPosition(initialLocation);
infowindow.open(map);
},function(){
handleNoGeolocation(browserSupportFlag);
});
}elseif(google.gears){
//TryGoogleGearsGeolocation
browserSupportFlag=true;
vargeo=google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position){
initialLocation=newgoogle.maps.LatLng(position.latitude,position.longitude);
contentString="LocationfoundusingGoogleGears";
map.setCenter(initialLocation);
infowindow.setContent(contentString);
infowindow.setPosition(initialLocation);
infowindow.open(map);
},function(){
handleNoGeolocation(browserSupportFlag);
});
}else{
//Browserdoesn'tsupportGeolocation
browserSupportFlag=false;
handleNoGeolocation(browserSupportFlag);
}
}
functionhandleNoGeolocation(errorFlag){
if(errorFlag==true){
initialLocation=newyork;
contentString="Error:TheGeolocationservicefailed.";
}else{
initialLocation=siberia;
contentString="Error:Yourbrowserdoesn'tsupportgeolocation.AreyouinSiberia?";
}
map.setCenter(initialLocation);
infowindow.setContent(contentString);
infowindow.setPosition(initialLocation);
infowindow.open(map);
}
</script>
</head>
<bodyonload="initialize()">
<divid="map_canvas"></div>
</body>
</html>