An explanation of how to develop WeChat mini programs and target the current city

巴扎黑
Release: 2017-09-12 10:54:09
Original
2861 people have browsed it

微信小程序 定位到当前城市

首先需要申请百度地图Geocoding API

Geocoding API包括地址解析和逆地址解析功能:

1.地理编码:即地址解析,由详细到街道的结构化地址得到百度经纬度信息,例如:“北京市海淀区中关村南大街27号”地址解析的结果是“lng:116.31985,lat:39.959836”。同时,地理编码也支持名胜古迹、标志性建筑名称直接解析返回百度经纬度,例如:“百度大厦”地址解析的结果是“lng:116.30815,lat:40.056885” ,通用的POI检索需求,建议使用Place API。

2.逆地理编码:即逆地址解析,由百度经纬度信息得到结构化地址信息,例如:“lat:31.325152,lng:120.558957”逆地址解析的结果是“江苏省苏州市虎丘区塔园路318号”。

代码:

Page({ 
 data:{ 
 city:'' 
 }, 
 onLoad:function(options){ 
 this.loadInfo(); 
 }, 
 loadInfo:function(){ 
 var page=this 
 wx.getLocation({ 
 type: 'wgs84', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标 
 success: function(res){ 
 // success 
 var longitude=res.longitude 
 var latitude=res.latitude 
 page.loadCity(longitude,latitude) 
 }, 
 fail: function() { 
 // fail 
 }, 
 complete: function() { 
 // complete 
 } 
 }) 
 }, 
 loadCity:function(longitude,latitude){ 
 var page =this 
 wx.request({ 
 url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak &location='+latitude+','+longitude+'&output=json', 
 data: {}, 
 header:{ 
 'Content-Type':'application/json' 
 }, 
 success: function(res){ 
 // success 
 console.log(res); 
 var city=res.data.result.addressComponent.city; 
 page.setData({city:city}); 
 }, 
 fail: function() { 
 // fail 
 }, 
 complete: function() { 
 // complete 
 } 
 }) 
 } 
})
Copy after login

index.wxml

<!--index.wxml--> 
<view class="container"> 
pw_city 
</view>
Copy after login

The above is the detailed content of An explanation of how to develop WeChat mini programs and target the current city. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template