GPS location services, map integration, and geographical functionality.
Access device GPS and location information.
/**
* Get current geographical location
* @param options - Location options
*/
function getLocation(options: GetLocationOptions): void;
interface GetLocationOptions {
type?: 'wgs84' | 'gcj02';
altitude?: boolean;
geocode?: boolean;
highAccuracyExpireTime?: number;
isHighAccuracy?: boolean;
success?: (result: GetLocationResult) => void;
fail?: (error: LocationError) => void;
complete?: () => void;
}
interface GetLocationResult {
latitude: number;
longitude: number;
speed?: number;
accuracy: number;
altitude?: number;
verticalAccuracy?: number;
horizontalAccuracy?: number;
address?: LocationAddress;
}
interface LocationAddress {
country: string;
province: string;
city: string;
district: string;
street: string;
streetNum: string;
poiName: string;
}
interface LocationError {
errMsg: string;
errCode: number;
}Usage Examples:
import uni from "@dcloudio/uni-app-plus";
// Get current location
uni.getLocation({
type: 'gcj02',
geocode: true,
success: (res) => {
console.log('Current location:', res.latitude, res.longitude);
console.log('Address:', res.address);
console.log('Accuracy:', res.accuracy + 'm');
// Use location data
this.setData({
latitude: res.latitude,
longitude: res.longitude,
address: res.address.city + res.address.district
});
},
fail: (error) => {
console.error('Failed to get location:', error);
// Handle different error types
switch (error.errCode) {
case 1:
console.log('User denied location access');
break;
case 2:
console.log('Network error');
break;
case 3:
console.log('Location timeout');
break;
}
}
});
// High accuracy location
uni.getLocation({
type: 'wgs84',
altitude: true,
isHighAccuracy: true,
highAccuracyExpireTime: 10000,
success: (res) => {
console.log('High accuracy location:');
console.log('Lat/Lng:', res.latitude, res.longitude);
console.log('Altitude:', res.altitude + 'm');
console.log('Speed:', res.speed + 'm/s');
}
});Allow users to choose locations from map interface.
/**
* Choose location from map interface
* @param options - Choose location options
*/
function chooseLocation(options?: ChooseLocationOptions): void;
interface ChooseLocationOptions {
latitude?: number;
longitude?: number;
keyword?: string;
success?: (result: ChooseLocationResult) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface ChooseLocationResult {
name: string;
address: string;
latitude: number;
longitude: number;
}Usage Example:
// Let user choose location
uni.chooseLocation({
latitude: 39.90923,
longitude: 116.397428,
success: (res) => {
console.log('Selected location:', res.name);
console.log('Address:', res.address);
console.log('Coordinates:', res.latitude, res.longitude);
// Save selected location
this.selectedLocation = {
name: res.name,
address: res.address,
coordinates: [res.longitude, res.latitude]
};
}
});Open system map application to display locations.
/**
* Open location in system map application
* @param options - Open location options
*/
function openLocation(options: OpenLocationOptions): void;
interface OpenLocationOptions {
latitude: number;
longitude: number;
scale?: number;
name?: string;
address?: string;
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}Usage Example:
// Open location in system map
uni.openLocation({
latitude: 39.90923,
longitude: 116.397428,
scale: 18,
name: 'Tiananmen Square',
address: 'Dongcheng District, Beijing',
success: () => {
console.log('Map opened successfully');
}
});Create map context for controlling map components.
/**
* Create map context for map component control
* @param mapId - Map component ID
* @returns MapContext instance
*/
function createMapContext(mapId: string): MapContext;
interface MapContext {
getCenterLocation(options?: GetCenterLocationOptions): void;
moveToLocation(options?: MoveToLocationOptions): void;
translateMarker(options: TranslateMarkerOptions): void;
includePoints(options: IncludePointsOptions): void;
getRegion(options?: GetRegionOptions): void;
getRotate(options?: GetRotateOptions): void;
getSkew(options?: GetSkewOptions): void;
getScale(options?: GetScaleOptions): void;
setCenterOffset(options: SetCenterOffsetOptions): void;
removeCustomLayer(options: RemoveCustomLayerOptions): void;
addCustomLayer(options: AddCustomLayerOptions): void;
addGroundOverlay(options: AddGroundOverlayOptions): void;
removeGroundOverlay(options: RemoveGroundOverlayOptions): void;
updateGroundOverlay(options: UpdateGroundOverlayOptions): void;
initMarkerCluster(options: InitMarkerClusterOptions): void;
addMarkersToCluster(options: AddMarkersToClusterOptions): void;
removeMarkersFromCluster(options: RemoveMarkersFromClusterOptions): void;
on(event: string, callback: Function): void;
off(event: string, callback?: Function): void;
}
interface GetCenterLocationOptions {
iconPath?: string;
success?: (result: CenterLocationResult) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface CenterLocationResult {
latitude: number;
longitude: number;
}
interface TranslateMarkerOptions {
markerId: number;
destination: {
latitude: number;
longitude: number;
};
autoRotate?: boolean;
rotate?: number;
duration?: number;
animationEnd?: () => void;
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface IncludePointsOptions {
points: Array<{
latitude: number;
longitude: number;
}>;
padding?: [number, number, number, number];
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}Usage Examples:
// Create map context
const mapCtx = uni.createMapContext('myMap');
// Get map center location
mapCtx.getCenterLocation({
success: (res) => {
console.log('Map center:', res.latitude, res.longitude);
}
});
// Move to specific location
mapCtx.moveToLocation({
latitude: 39.90923,
longitude: 116.397428
});
// Animate marker movement
mapCtx.translateMarker({
markerId: 1,
destination: {
latitude: 39.90923,
longitude: 116.397428
},
autoRotate: true,
duration: 2000,
animationEnd: () => {
console.log('Marker animation completed');
}
});
// Include multiple points in view
mapCtx.includePoints({
points: [
{ latitude: 39.90923, longitude: 116.397428 },
{ latitude: 39.91923, longitude: 116.407428 },
{ latitude: 39.89923, longitude: 116.387428 }
],
padding: [20, 20, 20, 20]
});
// Listen for map events
mapCtx.on('markertap', (event) => {
console.log('Marker tapped:', event.markerId);
});
mapCtx.on('regionchange', (event) => {
console.log('Map region changed:', event);
});Helper functions for geographical calculations.
// Distance calculation utility
const geoUtils = {
/**
* Calculate distance between two points
* @param lat1 - First point latitude
* @param lng1 - First point longitude
* @param lat2 - Second point latitude
* @param lng2 - Second point longitude
* @returns Distance in meters
*/
calculateDistance: (lat1: number, lng1: number, lat2: number, lng2: number) => number,
/**
* Convert coordinates between different systems
* @param coordinates - Coordinates to convert
* @param from - Source coordinate system
* @param to - Target coordinate system
* @returns Converted coordinates
*/
convertCoordinates: (coordinates: [number, number], from: 'wgs84' | 'gcj02', to: 'wgs84' | 'gcj02') => [number, number],
/**
* Check if point is within polygon
* @param point - Point coordinates
* @param polygon - Polygon vertices
* @returns True if point is inside polygon
*/
isPointInPolygon: (point: [number, number], polygon: [number, number][]) => boolean
};Usage Example:
// Calculate distance between two locations
const distance = geoUtils.calculateDistance(
39.90923, 116.397428, // Beijing Tiananmen
31.23037, 121.473701 // Shanghai Bund
);
console.log('Distance:', Math.round(distance / 1000) + 'km');
// Convert coordinates
const wgs84Coords = geoUtils.convertCoordinates(
[116.397428, 39.90923],
'gcj02',
'wgs84'
);
console.log('WGS84 coordinates:', wgs84Coords);
// Check if location is within area
const isInArea = geoUtils.isPointInPolygon(
[116.397428, 39.90923],
[
[116.39, 39.90],
[116.40, 39.90],
[116.40, 39.91],
[116.39, 39.91]
]
);
console.log('Is in area:', isInArea);interface MoveToLocationOptions {
latitude?: number;
longitude?: number;
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface GetRegionOptions {
success?: (result: RegionResult) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface RegionResult {
southwest: {
latitude: number;
longitude: number;
};
northeast: {
latitude: number;
longitude: number;
};
}
interface GetScaleOptions {
success?: (result: ScaleResult) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface ScaleResult {
scale: number;
}
interface SetCenterOffsetOptions {
offset: [number, number];
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface AddCustomLayerOptions {
layerId: string;
src: string;
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface InitMarkerClusterOptions {
enableDefaultStyle?: boolean;
zoomOnClick?: boolean;
gridSize?: number;
complete?: () => void;
}
interface AddMarkersToClusterOptions {
markers: MarkerClusterItem[];
clear?: boolean;
success?: (result: any) => void;
fail?: (error: any) => void;
complete?: () => void;
}
interface MarkerClusterItem {
id: number;
latitude: number;
longitude: number;
iconPath?: string;
width?: number;
height?: number;
callout?: {
content: string;
display: 'BYCLICK' | 'ALWAYS';
};
}interface CoordinateSystem {
WGS84: 'wgs84'; // World Geodetic System 1984
GCJ02: 'gcj02'; // Chinese coordinate system
}
interface LocationPermission {
GRANTED: 'granted';
DENIED: 'denied';
RESTRICTED: 'restricted';
}
interface LocationAccuracy {
HIGH: 'high';
MEDIUM: 'medium';
LOW: 'low';
}