推荐网站 https://html5demos.com/geo/
我们有时候可能希望首先获得用户的地理位置,然后根据不同的地理位置(更具针对性地)推送不同的信息等等。
下面这段代码就可以在你有jQuery的条件下alert()你所在的区域:
$.getScript("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js", function () { var province = remote_ip_info["province"] + '省'; alert(province); });
由于依赖的是jQuery,所以将$换成jQuery也可以达到相同的效果。
jQuery.getScript("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js", function () { var province = remote_ip_info["province"] + '省'; alert(province); });
我们可以看到调用了jQuery的一个方法,其中第一个参数是一个url,然后第二个参数时一个回调函数,这个回调函数中remote_ip_info["province"]即可得到用户所在的省份。
既然province时remote_ip_info对象的其中一个属性,那么remote_ip_info一定还有其他的属性,我们通过下面的代码来观察remote_ip_info这个对象究竟是什么:
$.getScript("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js", function () { console.log(remote_ip_info); });
在我的控制台中可以得到下面的信息:
即remote_ip_info对象中有city、country、desc 、disctrict、 isp、province、 ret、 start、 type等属性。 其中我们最为需要的恐怕是 中国-陕西-西安 了。
那为什么是这样的结果呢? 我们将第一个参数(url)输入到浏览器的地址栏中,可以看到,得到如下的代码:
var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"u4e2du56fd","province":"u9655u897f","city":"u897fu5b89","district":"","isp":"","type":"","desc":""};
我们可以看到他就是定义了这样的一个对象,我们得到的就是对应格式的对象。
使用谷歌地图。
<html> <meta name="viewport" content="width=620" /> <title>geolocation</title> <script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script> <article> <p>Finding your location: <span id="status">checking...</span></p> </article> <script> function success(position) { var s = document.querySelector('#status'); if (s.className == 'success') { // not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back return; } s.innerHTML = "found you!"; s.className = 'success'; var mapcanvas = document.createElement('div'); mapcanvas.id = 'mapcanvas'; mapcanvas.style.height = '400px'; mapcanvas.style.width = '560px'; document.querySelector('article').appendChild(mapcanvas); var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var myOptions = { zoom: 15, center: latlng, mapTypeControl: false, // mapTypeControl: true, navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions); var marker = new google.maps.Marker({ position: latlng, map: map, title:"You are here! (at least within a "+position.coords.accuracy+" meter radius)" }); } function error(msg) { var s = document.querySelector('#status'); s.innerHTML = typeof msg == 'string' ? msg : "failed"; s.className = 'fail'; // console.log(arguments); } if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(success, error); } else { error('not supported'); } </script> </html>