Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Location Selection with Gaode Maps in Uni-App

Tech May 8 3

Integrating Gaode Maps for Location Selection in Uni-App

When faced with unexpected service charges from a mapping provider, developers often need to quickly switch to alternative solutions. This guide demonstrates how to integrate Gaode Maps into a Uni-App project to implement precise location selection functionality.

Adding the Gaode Maps Mini Program Plugin

First, download the amap-wx.js file from the Gaode Maps Mini Program plugin documentation and place it in either your plugin or utils directory.

The file requires modifications to work properly with Uni-App. At the bottom of amap-wx.js, change the export statement to:

// module.exports.AMapWX = AMapWX;
export default { AMapWX };

Additionally, add this function at the top of the file:

export function AMapWX(a) {
    this.key = a.key;
    this.requestConfig = { key: a.key, s: 'rsx', platform: 'WXJS', appname: a.key, sdkversion: '1.2.0', logversion: '2.0' };
    this.MeRequestConfig = { key: a.key, serviceName: 'https://restapi.amap.com/rest/me' };
}

If you encounter issues during development, try replacing all instances of wx. with uni. in the amap-wx.js file.

Initializing the Map Component

After obtaining your Gaode Maps API key, initialize the map in your Vue 3 component's onMounted lifecycle hook:

<template>
    <view>
        <view class="map_container">
            <map
                :class="['map']"
                :id="'map'"
                :longitude="longitude"
                :latitude="latitude"
                :scale="14"
                :show-location="true"
                :markers="markers"
                @click="handleMapTap"></map>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as amapFile from '../../plugin/amap-wx.130';

const longitude = ref(null);
const latitude = ref(null);
const markers = ref([]);
const locationData = ref({});
const mapService = ref(null);
const apiKey = ref('your_api_key');
const nearbyLocations = ref([]);
const searchResults = ref([]);
const activeMarker = ref(-1);
const isSearching = ref(false);
const searchQuery = ref('');

onMounted(() => {
    mapService.value = new amapFile.AMapWX({ key: apiKey.value });
    fetchLocationInfo(true);
});

const fetchLocationInfo = (useResponseCoords) => {
    let coordinates = null;
    if (longitude.value != null && latitude.value != null) {
        coordinates = longitude.value + ',' + latitude.value;
    }

    mapService.value.getRegeo({
        iconPath: '../../static/marker.png',
        iconWidth: 22,
        iconHeight: 32,
        location: coordinates,
        success: (data) => {
            console.log('Location data', data[0].regeocodeData);
            if (useResponseCoords) {
                latitude.value = data[0].latitude;
                longitude.value = data[0].longitude;
            }
        },
        fail: function (error) {
            uni.showModal({ title: error.errMsg });
        },
    });
};

const handleMapTap = (event) => {
    console.log('Map tap event', event);
    latitude.value = event.detail.latitude;
    longitude.value = event.detail.longitude;
    fetchLocationInfo();
};
</script>

<style lang="scss" scoped>
.map_container {
    position: relative;
    top: 0;
    bottom: 80px;
    left: 0;
    right: 0;
}

.map {
    width: 100%;
    height: calc((100vh - 80px) * 0.45);
}
</style>

Configuring the Manifest File

If you encounter errors, update your manifest. file with the following configuration for the WeChat Mini Program platform:

"mp-weixin": {
    "appid": "your_mini_program_appid",
    "setting": {
        "urlCheck": false
    },
    "permission": {
        "scope.userLocation": {
            "desc": "Your location information will be used to display location-based features"
        }
    },
    "requiredPrivateInfos": ["chooseLocation", "getLocation"],
    "usingComponents": true,
    "lazyCodeLoading": "requiredComponents",
    "libVersion": "latest"
}

Remember to recompile your Mini Program after making these changes. If issues persist, clear the WeChat Developer Tools cache.

Rendering Nearby Locations

The response data contains a pois array that you can use to display nearby locations. This array contains the points of interest that will be rendered below the map component.

To display these locations, you can iterate through the pois array and create appropriate UI elements for each location entry.

<template>
    <view>
        
        
        <view class="location-list">
            <view 
                v-for="(location, index) in nearbyLocations" 
                :key="index"
                :class="['location-item', { active: activeMarker === index }]"
                @click="selectLocation(location, index)">
                <text class="location-name">{{ location.name }}</text>
                <text class="location-address">{{ location.address }}</text>
            </view>
        </view>
    </view>
</template>

<script setup>
// Previous imports and setup code

const selectLocation = (location, index) => {
    activeMarker.value = index;
    latitude.value = location.location.split(',')[1];
    longitude.value = location.location.split(',')[0];
    fetchLocationInfo();
};
</script>

<style lang="scss" scoped>
.location-list {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    border-top: 1px solid #eee;
    max-height: 35vh;
    overflow-y: auto;
}

.location-item {
    padding: 12px;
    border-bottom: 1px solid #f5f5f5;
    
    &.active {
        background-color: #f0f7ff;
    }
}

.location-name {
    font-size: 16px;
    font-weight: bold;
    display: block;
    margin-bottom: 4px;
}

.location-address {
    font-size: 14px;
    color: #666;
}
</style>

With these implementations, your Uni-app project will now have a fully functional location selection feature using Gaode Maps, allowing users to pick precise locations from a map view and nearby location list.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.