The mobile phone or PC uses the map of Gaode and Tencent to obtain the user's current location information

catalog

1, Introduction

2, Map of gaud

3, Tencent map

4, Summary

1, Introduction

Recently, in the project, it is necessary to use the function of obtaining the user's current geographic location information, obtaining the scene of the current user's location saved in the database, and supporting a variety of map positioning methods. Here, I use the method of system parameter configuration to temporarily realize the two ways of gaude map and Tencent map. Next, we will do one of the implementation methods of the two maps A summary.

2, Map of gaud

[a] Register the developer account of Gaode map to obtain the developer Key

Address of Gaode open platform: https://console.amap.com/dev/key/app

Choice: Web side (JS API) service platform

[b] Page introduction related JS

<script type="text/javascript" src="https://webapi.amap.com/maps?v=1 . 4.15 & key = fill in the application key "> < / script > in the previous step

[c] Get current location code

//Initialization of gaude map positioning
	initGdMap = () => {
		let mapObj = new AMap.Map('iCenter');
		mapObj.plugin('AMap.Geolocation', function() {
			let geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, // Use high precision positioning, default: true
				timeout: 10000,           // Stop positioning after 10 seconds, default: infinity
				maximumAge: 0,            // Location result cache 0 ms, default: 0
				convert: true,            // Automatically offset coordinates. The offset coordinates are gaude coordinates. The default value is true
				showButton: true,         // Display positioning button, default: true
				buttonPosition: 'LB',     // Positioning button docking position, default:'LB ', lower left corner
				buttonOffset: new AMap.Pixel(10, 20), // Offset of positioning button from the set docking position, default: Pixel(10, 20)
				showMarker: true,         // After successful positioning, the point mark will be displayed at the location to which the location is located. The default value is true
				showCircle: true,         // Circle indicates the positioning accuracy range after the positioning is successful, default: true
				panToLocation: true,      // After successful positioning, the location is used as the center point of the map. The default value is true
				zoomToAccuracy: true,       // After successful positioning, adjust the scope of the map to make the location and precision range visible. Default: false
			});
			mapObj.addControl(geolocation);
			geolocation.getCurrentPosition((status, result) => {
				if (status === 'complete') {
					//Reduced address result.formattedAddress Is the detailed address (province, city and county)
					// let currentAddress = result.addressComponent.building;
					console.log(result);
				} else {
					Toast.fail('seek failed', 1, () => {
						props.dispatch({
							type: 'studentWorkStudy/changeCurrentAddress',
							currentAddress: 'seek failed',
						});
					});
				}
			});
		});
	};

[d] Call result

Note: mobile terminal includes mobile phone, pad and other intelligent devices with GPS positioning chip (such as watch, speaker, etc.), and mobile terminal system includes iOS and Android. Successful positioning requires the following preconditions:

  1. System GPS on;
  2. The App or browser used has obtained the location permission;
  3. It is allowed to use location for the open page;
  4. For IOS 10 and above systems and some versions of Android, it is forbidden to locate under the domain name of non HTTPS protocol. Please upgrade the site to HTTPS as soon as possible;

Note that the above is only the prerequisite for successful positioning. Meeting these requirements does not necessarily mean successful positioning. Positioning is also affected by factors such as current position (indoor will affect GPS information), mobile phone signal and positioning authority. If you fail to locate during use, please refer to the FAQ: Geolocation's location process and the reason of location failure .

For more API functions related to Gode map, please refer to: https://lbs.amap.com/api/javascript-api/summary Learning.

3, Tencent map

To tell you the truth, Tencent map is not so accurate. If there is a website to access the HTTPS domain name, it is recommended to use Gaode map for positioning. Otherwise, the obtained location may have an error of 1-2 km.

[a] Register Tencent map developer account to obtain developer Key

Tencent map Developer Platform address: https://lbs.qq.com/dev/console/key/manage

[b] Page import related JS

<script type="text/javascript" src="https://map.qq.com/api/js?v=2 . exp & key = fill in the key "> < / script > of the previous step

[c] Get current location code

Considering that Tencent map is not very accurate, my approach is: first get the longitude and latitude information of the current location, and then make some minor adjustments, and then use the relevant WebService API interface of Tencent map to analyze the geographic location information in reverse.

Reverse address resolution (coordinate location description) reference document: https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder

Note: the following mapSecret is actually the Tencent map Key just applied for in the first step

//Initialize Tencent map positioning
	initTencentMap = (mapSecret = '') => {
		if (!mapSecret) {
			Toast.fail('Please set the map key in system management');
			return;
		}
		let props = this.props;
		//Initialize Tencent map positioning
		let geolocation = new qq.maps.Geolocation(mapSecret, 'ly-sm-mobile-ui');
		let options = { timeout: 8000 };
		geolocation.getLocation((position) => {
			//Slightly correct the latitude and longitude deviation of Tencent map
			let latitude = position.lat + 0.00134;
			let longitude = position.lng + 0.01191;
			props.dispatch({
				type: 'studentWorkStudy/getAddressList',
				params: {
					location: `${latitude},${longitude}`,
				},
				callback: data => {
					if (data) {
						let dataMap = JSON.parse(data);
                        console.log(dataMap.result);
						//Address description
						// let address = dataMap.result.address || '';
						// Description method optimized by Tencent map
						let recommendAddress = dataMap.result.formatted_addresses.recommend || '';
						//For more parameters, please refer to: https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder
						props.dispatch({
							type: 'studentWorkStudy/changeCurrentAddress',
							currentAddress: recommendAddress,
						});
					}
				},
			});
		}, () => {
			Toast.fail('seek failed', 1, () => {
				props.dispatch({
					type: 'studentWorkStudy/changeCurrentAddress',
					currentAddress: 'seek failed',
				});
			});
		}, options);
	};

The back-end service needs to cooperate with the back-end service to initiate a WebService request through reverse address resolution. The request URL is just like the following, except that the latitude and longitude information on the URL is the longitude and latitude of the current location obtained.

Call example: GET request example. Note that the parameter value should be URL encoded
https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1

Request parameter description:

parameter Required explain Examples
location yes Location coordinates, format:
Location = lat < latitude >, LNG < longitude >
location= 39.984154,116.307490
get_poi no Do you want to return to the surrounding POI list
1. Return; 0 do not return (default)
get_poi=1
poi_options no Used to control the POI list:
1 poi_options=address_format=short
Return the short address, and return the long address by default
2 poi_options=radius=5000
Radius, range 1-5000 (m)
3 poi_options=page_size=20
Number of pages per page, value range 1-20
4 poi_options=page_index=1
Page number, value range 1-20
Note: page when paging_ Size and page_index parameter needs to be used at the same time
5 poi_options=policy=1/2/3/4/5
Control the return scene,
policy=1 [default] focuses on landmark + main road + short distance POI, and focuses on describing the current position;
policy=2 home scenario: select the appropriate POI and refine the delivery address to the building;
policy=3 travel scenario: filter out poi (such as POI in some scenic spots) that are difficult for vehicles to reach, and add POI of road entrance, intersection and large area entrance and exit. The ranking will be automatically optimized according to the user click of real API big users.
policy=4 social check-in scenario, which prioritizes the popular places where users sign in.
policy=5 location sharing scenarios, which are often used by users to prioritize popular locations in scenarios such as sending location and location sharing
6 poi_options=category = category 1, category 2,
Specify classification, separate multiple keywords with commas;
(see Appendix for support categories)
[single parameter writing example]:
poi_options=address_format=short
[English semicolon interval of multiple parameters, example of writing method]:
poi_options=address_format=short;radius=5000;
page_size=20;page_index=1;policy=2
key yes Development Key key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77
output no Return format: support JSON / JSON P, default JSON output=json
callback no JSONP callback function callback=function1

Return result example:

{
    "status": 0,
    "message": "query ok",
    "request_id": "c165b6de-b9d9-11ea-8207-5254004df5fd",
    "result": {
        "location": {
            "lat": 39.984154,
            "lng": 116.30749
        },
        "address": "66 Beisihuan West Road, Haidian District, Beijing",
        "formatted_addresses": {
            "recommend": "Zhongguancun China Technology Trading Building, Haidian District(Caihefang Road)",
            "rough": "Zhongguancun China Technology Trading Building, Haidian District(Caihefang Road)"
        },
        "address_component": {
            "nation": "China",
            "province": "Beijing",
            "city": "Beijing",
            "district": "Haidian District",
            "street": "North Fourth Ring Road West",
            "street_number": "66 North Fourth Ring Road West"
        },
        "ad_info": {
            "nation_code": "156",
            "adcode": "110108",
            "city_code": "156110000",
            "name": "China,Beijing,Beijing,Haidian District",
            "location": {
                "lat": 40.045132,
                "lng": 116.375
            },
            "nation": "China",
            "province": "Beijing",
            "city": "Beijing",
            "district": "Haidian District"
        },
        "address_reference": {
            "business_area": {
                "id": "14178584199053362783",
                "title": "Zhongguancun",
                "location": {
                    "lat": 39.980598,
                    "lng": 116.310997
                },
                "_distance": 0,
                "_dir_desc": "within"
            },
            "famous_area": {
                "id": "14178584199053362783",
                "title": "Zhongguancun",
                "location": {
                    "lat": 39.980598,
                    "lng": 116.310997
                },
                "_distance": 0,
                "_dir_desc": "within"
            },
            "crossroad": {
                "id": "529979",
                "title": "Haidian Street/Caihefang Road(intersection)",
                "location": {
                    "lat": 39.982498,
                    "lng": 116.30809
                },
                "_distance": 185.8,
                "_dir_desc": "north"
            },
            "town": {
                "id": "110108012",
                "title": "Haidian Street",
                "location": {
                    "lat": 39.974819,
                    "lng": 116.284409
                },
                "_distance": 0,
                "_dir_desc": "within"
            },
            "street_number": {
                "id": "595672509379194165901290",
                "title": "66 North Fourth Ring Road West",
                "location": {
                    "lat": 39.984089,
                    "lng": 116.308037
                },
                "_distance": 45.8,
                "_dir_desc": ""
            },
            "street": {
                "id": "9217092216709107946",
                "title": "Caihefang Road",
                "location": {
                    "lat": 39.97921,
                    "lng": 116.308411
                },
                "_distance": 46.6,
                "_dir_desc": "west"
            },
            "landmark_l2": {
                "id": "3629720141162880123",
                "title": "China Technology Exchange Building",
                "location": {
                    "lat": 39.984104,
                    "lng": 116.307503
                },
                "_distance": 0,
                "_dir_desc": "within"
            }
        },
        "poi_count": 10,
        "pois": [
            {
                "id": "3629720141162880123",
                "title": "China Technology Exchange Building",
                "address": "66 Beisihuan West Road, Haidian District, Beijing",
                "category": "Real estate community:Commercial buildings",
                "location": {
                    "lat": 39.984104,
                    "lng": 116.307503
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 0,
                "_dir_desc": "within"
            },
            {
                "id": "9969038414753335812",
                "title": "Tencent Technology(Beijing)limited company(China Technology Trading Building)",
                "address": "5, the third pole building, China Technology Exchange building, No.66, Beisihuan West Road, Haidian District, Beijing-11 layer",
                "category": "Company:Corporate enterprise",
                "location": {
                    "lat": 39.984131,
                    "lng": 116.307503
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 0,
                "_dir_desc": "within"
            },
            {
                "id": "2845372667492951071",
                "title": "China Technology Exchange Building A Seat",
                "address": "66 Beisihuan West Road, Haidian District, Beijing",
                "category": "Real estate community:Commercial buildings",
                "location": {
                    "lat": 39.984329,
                    "lng": 116.307419
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 20.4,
                "_dir_desc": ""
            },
            {
                "id": "3724888736111897241",
                "title": "Wanxue Education Group",
                "address": "China Technology Trading Building, 66 Beisihuan West Road, Haidian District, Beijing",
                "category": "Company:Company",
                "location": {
                    "lat": 39.984085,
                    "lng": 116.307426
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 9.2,
                "_dir_desc": ""
            },
            {
                "id": "13477589832396847863",
                "title": "product·Coffee",
                "address": "In the hall on the first floor of China Technology Exchange building, No.66, Beisihuan West Road, Haidian District, Beijing",
                "category": "Entertainment and leisure:café",
                "location": {
                    "lat": 39.984192,
                    "lng": 116.30735
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 12.5,
                "_dir_desc": ""
            },
            {
                "id": "3187032738687555052",
                "title": "Zhongguancun Chuangye Street",
                "address": "Haidian West St, Haidian District, Beijing",
                "category": "shopping:Commercial pedestrian street",
                "location": {
                    "lat": 39.983013,
                    "lng": 116.306732
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 36.3,
                "_dir_desc": "northeast"
            },
            {
                "id": "7246616758286733108",
                "title": "Christian Church(Caihefang Road)",
                "address": "9 caihefang Road, Haidian District, Beijing",
                "category": "scenic spot:church",
                "location": {
                    "lat": 39.983135,
                    "lng": 116.30764
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 69.5,
                "_dir_desc": "north"
            },
            {
                "id": "12925244666643621769",
                "title": "China Technology Exchange Building B Seat",
                "address": "66 Beisihuan West Road, Haidian District, Beijing",
                "category": "Real estate community:Commercial buildings",
                "location": {
                    "lat": 39.983906,
                    "lng": 116.307556
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 28.2,
                "_dir_desc": ""
            },
            {
                "id": "12689244359326172642",
                "title": "Garage coffee",
                "address": "2 / F, building 6, Chuangye street, Zhongguancun, Haidian District, Beijing",
                "category": "Entertainment and leisure:café",
                "location": {
                    "lat": 39.983898,
                    "lng": 116.306908
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 57.1,
                "_dir_desc": "northeast"
            },
            {
                "id": "2926578115367138813",
                "title": "Wusheng pork liver noodles",
                "address": "66 Beisihuan West Road, Haidian District, Beijing",
                "category": "delicious food:Snacks",
                "location": {
                    "lat": 39.984184,
                    "lng": 116.307503
                },
                "ad_info": {
                    "adcode": "110108",
                    "province": "Beijing",
                    "city": "Beijing",
                    "district": "Haidian District"
                },
                "_distance": 3.6,
                "_dir_desc": ""
            }
        ]
    }
}

Through the reverse address resolution, we can also obtain the location collection information of the current location, which is very useful in some business scenarios.

[d] Positioning results

For more Tencent map related API s, please refer to: https://lbs.qq.com/webApi/javascriptGL/glGuide/glOverview Learning.

4, Summary

The above is about the function of getting the user's current position from the map of Gaode and Tencent. In brief, it is basically carried out according to the official documents. Here is just a summary. When you use it later, you can turn it out and have a look. There are many more sophisticated operations that you can learn from the corresponding official documents.

Tags: Amap Mobile JSON Javascript

Posted on Mon, 29 Jun 2020 03:37:22 -0400 by ragtek