Geographic location and maps (uni.getLocation, map component)
Application of Geographic Location and Maps in uni-app
uni-app provides the uni.getLocation
API and map
component to implement location-related functionalities. These features are very common in modern mobile applications, such as location services in food delivery apps or displaying nearby shared bikes.
Detailed Explanation of the uni.getLocation
API
uni.getLocation
is the core API in uni-app for obtaining the device's current location. It supports retrieving location information such as latitude, longitude, speed, and altitude.
Basic Usage
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log('Current longitude: ' + res.longitude);
console.log('Current latitude: ' + res.latitude);
},
fail: function (err) {
console.error('Failed to get location: ', err);
}
});
Parameter Description
type
: Coordinate typewgs84
: Returns GPS coordinatesgcj02
: Returns coordinates from the Chinese State Bureau of Surveying and Mapping
altitude
: Whether to retrieve altitude information (default: false)geocode
: Whether to resolve address information (default: false)highAccuracyExpireTime
: Timeout duration for high-precision positioning (in milliseconds)
Practical Application Example
// Get the current location and display the detailed address
getCurrentLocation() {
uni.getLocation({
type: 'gcj02',
geocode: true,
success: (res) => {
this.longitude = res.longitude
this.latitude = res.latitude
this.address = res.address
uni.showToast({
title: 'Location obtained successfully',
icon: 'success'
})
},
fail: (err) => {
console.error(err)
uni.showToast({
title: 'Failed to get location',
icon: 'none'
})
}
})
}
Guide to Using the map
Component
The map
component in uni-app is based on native maps of each platform. It is powerful but requires attention to platform differences.
Basic Properties
<map
id="myMap"
:longitude="longitude"
:latitude="latitude"
scale="16"
show-location
markers="markers"
@markertap="handleMarkerTap"
style="width: 100%; height: 300px;">
</map>
Detailed Explanation of Common Properties
-
Basic Positioning Properties
longitude
: Center longitudelatitude
: Center latitudescale
: Zoom level (3-20)
-
Control Display
show-location
: Displays the current location point with directionshow-compass
: Displays the compassenable-zoom
: Whether zooming is supportedenable-scroll
: Whether dragging is supported
-
Overlays
markers
: Array of markerspolyline
: Array of routescircles
: Array of circular overlayscontrols
: Array of controls
Example of Markers
data() {
return {
markers: [{
id: 1,
latitude: 39.90469,
longitude: 116.40717,
title: 'Beijing',
iconPath: '/static/location.png',
width: 30,
height: 30,
callout: {
content: 'City Center of Beijing',
color: '#ffffff',
bgColor: '#007AFF',
padding: 5,
borderRadius: 4
}
}]
}
}
Map Interaction and Event Handling
The map
component supports various interactive events, enabling rich user experiences.
Common Events
<map
@tap="handleMapTap"
@markertap="handleMarkerTap"
@regionchange="handleRegionChange"
@callouttap="handleCalloutTap">
</map>
Event Handling Example
methods: {
handleMapTap(e) {
console.log('Map click coordinates: ', e.detail)
this.addMarker(e.detail.latitude, e.detail.longitude)
},
handleMarkerTap(e) {
const markerId = e.markerId
uni.showModal({
title: this.markers[markerId].title,
content: 'You clicked this marker'
})
},
addMarker(lat, lng) {
const newMarker = {
id: Date.now(),
latitude: lat,
longitude: lng,
iconPath: '/static/marker.png'
}
this.markers.push(newMarker)
}
}
Implementing Advanced Map Features
Drawing Routes
// Define polyline in data
polyline: [{
points: [
{latitude: 39.90469, longitude: 116.40717},
{latitude: 39.91469, longitude: 116.41717}
],
color: '#FF0000',
width: 2,
dottedLine: false
}]
Circular Overlays
circles: [{
latitude: 39.90469,
longitude: 116.40717,
color: '#FF0000AA',
fillColor: '#00FF0055',
radius: 500,
strokeWidth: 1
}]
Map Controls
controls: [{
id: 1,
iconPath: '/static/refresh.png',
position: {
left: 10,
top: 10,
width: 30,
height: 30
},
clickable: true
}]
Performance Optimization and Considerations
-
Map Performance Optimization
- Avoid frequently updating map data
- Use cover-view appropriately to overlay native components
- Consider using marker clustering for large numbers of markers
-
Common Issues
- iOS requires configuration of location permission descriptions
- Android requires location permission requests
- Note HTTPS restrictions during real-device debugging
// Example of checking location permission
checkLocationPermission() {
uni.authorize({
scope: 'scope.userLocation',
success: () => {
this.getCurrentLocation()
},
fail: () => {
uni.showModal({
title: 'Prompt',
content: 'Need to access your location information',
success: (res) => {
if (res.confirm) {
uni.openSetting()
}
}
})
}
})
}
Platform Differences and Compatibility Handling
Different platforms have varying map implementations, requiring special attention:
-
WeChat Mini Program
- Supports rich overlay types
- Requires configuration of valid domains
- Supports same-layer rendering of map components
-
H5 Platform
- Based on the browser's Geolocation API
- Requires HTTPS environment
- Accuracy may be lower
-
App Platform
- Uses native map controls
- Most comprehensive functionality
- Requires permission configuration
// Example of platform-compatible code
getMapProvider() {
// #ifdef MP-WEIXIN
return 'wx'
// #endif
// #ifdef H5
return 'h5'
// #endif
// #ifdef APP-PLUS
return 'native'
// #endif
}
Implementation in Real Business Scenarios
Scenario 1: Displaying Nearby Stores
// Get nearby stores
getNearbyShops() {
uni.getLocation({
type: 'gcj02',
success: (res) => {
uni.request({
url: 'https://api.example.com/nearby-shops',
data: {
lat: res.latitude,
lng: res.longitude,
radius: 1000 // Within 1 km
},
success: (shopRes) => {
this.shops = shopRes.data
this.updateMapMarkers()
}
})
}
})
},
updateMapMarkers() {
this.markers = this.shops.map(shop => ({
id: shop.id,
latitude: shop.location.lat,
longitude: shop.location.lng,
iconPath: '/static/shop.png',
title: shop.name
}))
}
Scenario 2: Tracking Movement
// Record movement trajectory
startTracking() {
this.trackPoints = []
this.trackingInterval = setInterval(() => {
uni.getLocation({
type: 'wgs84',
success: (res) => {
this.trackPoints.push({
latitude: res.latitude,
longitude: res.longitude
})
this.updateTrackLine()
}
})
}, 5000) // Record every 5 seconds
},
updateTrackLine() {
this.polyline = [{
points: this.trackPoints,
color: '#0000FF',
width: 4
}]
},
stopTracking() {
clearInterval(this.trackingInterval)
}
Map Plugins and Extensions
The uni-app ecosystem includes many map-related plugins to enhance functionality:
-
Third-Party Map Plugins
- AMap (Gaode Map) plugin
- Baidu Map plugin
- Tencent Map plugin
-
Feature Extension Plugins
- Map point selection plugin
- Heatmap plugin
- 3D map plugin
// Example of using the AMap plugin
const amap = require('@/common/amap-wx.js')
const myAmap = new amap.AMapWX({
key: 'Your AMap key'
})
myAmap.getRegeo({
location: `${longitude},${latitude}`,
success: (data) => {
console.log('Reverse geocoding result:', data)
}
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn