手机端H5获取当前城市的方法

移动端的H5页面提供了定位的功能,那么如何实现一个最简单的需求-----获取用户当前城市?

你可能搜一下就会找到N篇博客介绍,但是你会发现你看完大段代码之后还是没搞清楚,为了便于大家理解,我精简了代码,只保留了必要的部分。

1、在html页面引入百度地图API(文档地址:http://developer.baidu.com/map/wiki/index.php?title=jspopular/guide/introduction

<script src="http://api.map.baidu.com/api?ak=你的AK码&v=2.0&services=false"></script> 

2、js代码使用h5的geolocation方法获取坐标,然后使用百度api的getlocation方法翻译成你想要得结果(不准确)

 navigator.geolocation.getCurrentPosition(function (position) {
          var lat = position.coords.latitude;
          var lon = position.coords.longitude;
          var point = new BMap.Point(lon, lat);  // 创建坐标点
          // 根据坐标得到地址描述
          var myGeo = new BMap.Geocoder();
          myGeo.getLocation(point, function (result) {
              var city = result.addressComponents.city;
              $('body').html(city);
         });
     });

 3.用高德地图(比较准确)

html

     <div id="container" style="display: none;"></div>

js

	<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.2&key=您的key"></script>
 var map, geolocation;//加载地图,调用浏览器定位服务
	map = new AMap.Map('container', {
	resizeEnable: true
	});
	map.plugin('AMap.Geolocation', function() {
	   geolocation = new AMap.Geolocation({
			enableHighAccuracy: true, 
			timeout: 10000 
			});
	    geolocation.getCityInfo(getCity)
	});
	function getCity(status, result) {
		if(status!='complete'){
		  console.log(status)
		  showToast('定位失败');
		}else{
		  console.log(result.city)
		}
	}

4、打开手机试一下吧

如果不需要精准的定位,还有一种通过IP地址获取当前城市的方法,采用新浪的api接口。(不准确)

<script src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script>
<script>
    var city = remote_ip_info['city'];
    alert(city)
</script>

猜你喜欢

转载自blog.csdn.net/MeetLunay/article/details/84977844
今日推荐