微信小程序-根据经纬度在地图定位标记

1. js

// pages/index/index.js Page({ data: { longitude: 113.324520, latitude: 23.099994, markers: [{ id: 0, latitude: 23.099994, longitude: 113.324520, iconPath: '/resources/location.png', width: 30, height: 30 }], cityList: [ { name: '北京', longitude: 116.407526, latitude: 39.904030 }, { name: '上海', longitude: 121.473701, latitude: 31.230416 }, { name: '广州', longitude: 113.264394, latitude: 23.129107 }, { name: '深圳', longitude: 114.057865, latitude: 22.543096 } ] }, onLoad: function() { wx.getSetting({ success: res => { if (!res.authSetting['scope.userLocation']) { wx.authorize({ scope: 'scope.userLocation', success() { this.getLocation(); }, fail() { // 处理授权失败的情况 } }); } else { this.getLocation(); } } }); }, getLocation: function() { let that = this; wx.getLocation({ type: 'wgs84', success: function(res) { that.setData({ longitude: res.longitude, latitude: res.latitude, markers: [{ id: 0, latitude: res.latitude, longitude: res.longitude, iconPath: '/resources/location.png', width: 30, height: 30 }] }); } }); }, changeLocation: function(e) { let index = e.currentTarget.dataset.index; let city = this.data.cityList[index]; this.setData({ longitude: city.longitude, latitude: city.latitude, markers: [{ id: 1, latitude: city.latitude, longitude: city.longitude, iconPath: '/resources/location.png', width: 30, height: 30 }] }); } });
2.json
{ "usingComponents": { "navigation-bar": "/components/navigation-bar/navigation-bar" } }
3. wxml

<!-- pages/index/index.wxml --> <view class="container"> <map id="myMap" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" markers="{{markers}}" style="width: 100%; height: 662rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx"></map> <view class="city-names"> <button wx:for="{{cityList}}" wx:key="index" bindtap="changeLocation" data-index="{{index}}">{{item.name}}</button> </view> </view>
4. wxss

/* pages/index/index.wxss */ .container { display: flex; flex-direction: column; height: 100vh; /* 使用视口高度单位 */ } #myMap { flex: 1; /* 地图占据剩余空间 */ } .city-names { flex: 1; overflow-y: auto; padding: 10px; background-color: #fff; } .city-names button { padding: 10px; border-bottom: 1px solid #eee; }
5 . app.json

{ "pages": [ "pages/index/index" ], "window": { "navigationBarTextStyle": "black", "navigationStyle": "custom" }, "style": "v2", "renderer": "webview", "componentFramework": "glass-easel", "sitemapLocation": "sitemap.json", "lazyCodeLoading": "requiredComponents", "permission": { "scope.userLocation": {"desc": "你的位置信息将用于小程序定位功能,以便为你提供更准确的服务"} } }

浙公网安备 33010602011771号