Driving route planning based on location and location search

A mobile terminal example developed based on Gaode map JSAPI simulates the following scenarios: obtain the user's current location through positioning, fine tune the location after successful positioning, and let the user select the current location through search if positioning fails; Then let the user select the destination through search, and plan the route from the current location to the destination after obtaining the current location and destination.

Experience address

Preview




Scenario implementation idea:

Firstly, the user's current accurate position is obtained through the getCurrentPosition interface of Geolocation positioning component. If the positioning is successful, the obtained accurate position is marked as the starting position. If the positioning fails, the user's city information is obtained through getCityInfo method of Geolocation, and then the city center point is marked as the starting position;

Then, after marking, open the fine-tuning function of the starting point position. The fine-tuning function is realized by using custom controls. Add a point picture consistent with the starting point style at the center point of the map, so that when the map is dragged, the point will not move with the map. After dragging, remove the control, Set the position of the starting point mark as the center point of the map, drag and drop the obtained longitude and latitude, and use Geocoder's getAddress method to obtain the specific address letter;

Then, a POI selection function is realized by using Autocomplete input prompt component and PlaceSearch search component. Users can get their location and destination location through this POI selection interface;

Finally, after the current location and destination are determined, the Driving driving route planning component is used to plan the travel route.

Implementation process

1. Loading of jsapi and related components

When developing Web applications using JSAPI, you need to reference the JSAPI entry file into the page. If you need to load some plug-ins at the same time, you can add the plugin parameter to the JSAPI reference:

<script 
        type="text/javascript" 
        src='http://webapi.amap.com/maps?v=1.3&plugin=AMap.Geolocation,AMap.ToolBar,AMap.Geocoder,AMap.PlaceSearch,AMap.Autocomplete,AMap.Driving&key=e07ffdf58c8e8672037bef0d6cae7d4a'></script>

2. Page layout

Firstly, a single page with left and right layout is realized through html and css, with one interface on the left and right. The left interface is used to display the map, positioning result adjustment, starting and ending point display and route planning result display, and the right page is used to realize the location selection function, including input prompt box and POI search result display panel. In the code, showLeftView and showRightView are used to switch the left and right interfaces.

3. Realization of positioning function

Geolocation component is mainly used for location. There are two common methods in this component: getCurrentPosition method to obtain the exact location of the user and getCityInfo method to obtain the city information of the user. First, we get the exact location of the user through getCurrentPosition. If we can't get it, we can use getCityInfo method to get the city information of the user. The obtained precise positioning position or city center position will be used as the initial starting position:

//Add a positioning component to obtain the current precise location of the user
var geolocation = new AMap.Geolocation({
 	showCircle: false, //Circles that do not display positioning results
 	showMarker: false, //Marking of unrealistic positioning results
 	showButton: false, //Positioning button of unrealistic component
 	timeout: 5000 //Browser positioning timeout 5s
});
geolocation.getCurrentPosition(function(status, result) {
	if (status == 'complete') {
		onLocateSuccess(result) //Successful positioning
	} else if (status == 'error') {
		//seek failed
		if (result.message.indexOf('Geolocation permission denied.') !== -1) {
        //Geolocation permission denied. It indicates that the user has disabled the location permission of the browser or APP or has turned off the mobile phone as a service
        //Or the current page is a non secure page. Chrome or IOS10 and other systems will disable the location request of non secure pages. If your page does not support HTTPS, please upgrade as soon as possible
        //A secure page refers to a Web site that supports HTTPS and is opened through the HTTPS protocol. Security pages also include local pages
			showTip('Hello, please open the location permission of the current application in the privacy settings of the system.');
		} else {
			showTip('Unable to get exact location,Will locate your city.');
		}
		onLocateFailed();
	}http://www.biyezuopin.vip
})
//City positioning after positioning failure
var onLocateFailed = function() {
 	geolocation.getCityInfo(function(status, result) {
 		map.setZoom(14);
 		showLocation(result.center); //Show starting marker at city center
 		placeSearch.setCity(result.citycode);
 		autoComplete.setCity(result.citycode);
 	})
};
//Successful positioning
var onLocateSuccess = function(result) {
 	showTip('Successful positioning,Drag the map to fine tune.');
 	showLocation(result.position); //Display the starting marker in the positioning result
 	var city = result.addressComponent.city;
 	var province = result.addressComponent.province;
 	var district = result.addressComponent.district;
 	var township = result.addressComponent.township;
 	showOriginAddress(result.formattedAddress.replace(province, '').replace(city, '').replace(district, '').replace(township, ''))
 	origin.position = result.position;
 	placeSearch.setCity(result.addressComponent.citycode);
 	autoComplete.setCity(result.addressComponent.citycode);
};http://www.biyezuopin.vip

4. Implementation of dragging the map to adjust the starting point position

First, create a custom control. The custom control of JSAPI only needs to implement addTo and removeFrom methods. The function of this custom control is very simple, which is to display a picture exactly like the starting point mark in the center of the map.

//Custom control for fine adjustment of positioning position
var content = document.createElement('div');
content.innerHTML = "<img src='./images/starts.png'>";
content.className = 'customControl';
var customControl = { //To customize the control, you need to implement the addTo and removeFrom methods
 	dom: content,
 	addTo: function() {
 		map.getContainer().appendChild(customControl.dom);
 	},
 	removeFrom: function() {
 		if (customControl.dom.parentNode == map.getContainer()) {
 			map.getContainer().removeChild(customControl.dom);
 		}
 	}
}

Then bind dragstart and moveend events to the map when adjustment is needed. The event callback of dragstart hides the starting point marker and adds custom controls. The event callback of moveend removes the custom space, sets the location of the starting point marker, and performs inverse geocoding to obtain the address information of the new location:

//Add controls when dragging starts, hide the start marker, and register drag end events
var onMapDragStart = function() {
 	startMarker.hide();
 	map.addControl(customControl);
 	map.on('moveend', onMapMoveEnd);
};
//At the end of dragging, set the starting point as the map center, and use the inverse geocoding interface to obtain the address information of the current location
var onMapMoveEnd = function() {
 	map.removeControl(customControl);
 	startMarker.setPosition(map.getCenter());
 	startMarker.show();
 	var position = map.getCenter();
 	geocoder.getAddress(position, function(status, result) { //Reverse geocoding to obtain address information according to longitude and latitude
 		result = result.regeocode;
 		var city = result.addressComponent.city;
 		var province = result.addressComponent.province;
 		var district = result.addressComponent.district;
 		var township = result.addressComponent.township;
 		showOriginAddress(result.formattedAddress
            .replace(province, '')
            .replace(city, '')
            .replace(district, '')
            .replace(township, ''))
 		origin.position = position;
 		placeSearch.setCity(result.addressComponent.citycode);
 		autoComplete.setCity(result.addressComponent.citycode);
 	})http://www.biyezuopin.vip
};

var startAdjustOrigin = function() {
 	map.on('dragstart', onMapDragStart);
}
var stopAdjustOrigin = function() {
 	map.off('dragstart', onMapDragStart);
 	map.off('moveend', onMapMoveEnd);
}

5. Realization of search and point selection function

Two components are used to search and select points. One is the Autocomplete input prompt component, which assigns an input element to it, and the relevant prompt location will be automatically displayed when text is entered; The other is the PlaceSearch component, which sets the panel attribute. After calling search, the returned data will be automatically displayed in the div specified by the panel

//Input prompt component. After inputting text in searchInput, relevant location prompt will be automatically displayed
var autoComplete = new AMap.Autocomplete({
	input: searchInput,
	citylimit: true,
	noshowDistrict: true
});
//POI search component is used to search relevant POI information according to the value in the input box
var placeSearch = new AMap.PlaceSearch({
	panel: 'searchResult',
	pageSize: 8,
	radius: 10000,
	citylimit: true
});

When we open the search interface, we bind the select event to the input prompt component. When a prompt item is clicked and selected, we will execute the event callback. In the event callback, we call the search method of placesearch to search for keywords, and the search results will be automatically displayed in the # searchResult div. At the same time, bind a listElementClick event to placesearch. When any element in the result list is clicked, the event callback will be executed. In the event callback, we will execute the callback operation selected by POI and switch the interface to the map interface

//Click the start or end input box to open the search interface, and execute the onSelectCallback callback when clicking any POI in the search results
var onInputClick = function(initText, onSelectCallback) {
	if (initText !== 'Your position' && initText !== 'Where are you going?') {
		searchInput.value = initText;
	} else {
		searchInput.value = '';
	}
	showRightView(); //Open the search interface
	//When one is selected in the input prompt result list, the keyword search of POI search is triggered
	autoComplete.selectHandler = AMap.event.addListener(autoComplete, 'select', function(e) {
		placeSearch.search(e.poi.name)
	});
	//When one is selected in the POI search result list, the onSelectCallback callback is triggered
	placeSearch.listElementClickHandler = AMap.event.addListener(placeSearch, 'listElementClick', function(e) {
		onSelectCallback(e.data);
		showLeftView();
	})

};

onSelectCallback is the callback function that we pass in when we open the search interface. Click the start point and end point to pass different callbacks onOriginSelected and onDestinationSelected respectively:

//Click and select a POI from the search results and execute. Set the starting position as the position of POI
var onOriginSelected = function(poi) {
	origin.position = poi.entr_location || poi.location;
	origin.innerHTML = poi.name;
	startMarker.setPosition(origin.position);
	if (destination.position) {
		driving.search(origin.position, destination.position)
	} else {
		map.setFitView();
		startAdjustOrigin();
	}

};
//Click and select a POI from the search results, and set the end position as the position of POI
var onDestinationSelected = function(poi) {
	destination.position = poi.entr_location || poi.location;
	destination.innerHTML = poi.name;
	endMarker.setMap(map);
	endMarker.setPosition(destination.position);
	if (origin.position && destination.position) {
		driving.search(origin.position, destination.position)
	}
};
//Execute after positioning and enable search
var enableSearch = function() {
	//Click the start point input to open the search interface
	AMap.event.addDomListener(origin, 'click', function(e) {
		stopAdjustOrigin();
		if (origin.innerHTML !== 'Your position') {
			//If there is already a starting position, the search page opens and the surrounding search results of the positioning position are displayed by default
			placeSearch.searchNearBy('', origin.position);
		}
		onInputClick(origin.innerHTML, onOriginSelected)
	});
	//Click the end point input to open the search interface
	AMap.event.addDomListener(destination, 'click', function() {
		stopAdjustOrigin();
		if (destination.innerHTML !== 'Where are you going?') {
			//If there is already a destination, the search page opens and the surrounding search results of the destination are displayed by default
			placeSearch.searchNearBy('', destination.position);
		}
		onInputClick(destination.innerHTML, onDestinationSelected)
	});
}

6. Realization of driving route planning

The driving component needs to be used for driving route planning. Because we have created the Marker of starting and ending points, we set hideMarkers to hide the starting and ending points of the component. After the map attribute is passed in, the result of route planning will be automatically displayed on the map object. Then, in onOriginSelected and onDestinationSelected functions, we first determine whether the end point is located. After all, we can get the search method called driving.

  	//Create driving route planning component
     var driving = new AMap.Driving({
         map:map,
         hideMarkers:true
     });
 
     if (origin.position && destination.position) {
 		driving.search(origin.position, destination.position)
 	}

Other instructions

About the developer key of JSAPI:

Developer key is a string of characters that developers must fill in when using JSAPI to develop map applications. Only the correct and effective key can ensure the normal operation of all functions and service interfaces. This example does not fill in a valid developer key. In order to make the relevant examples related to the service run normally, first register the Gaode map developer account, then apply for the developer key of JSAPI and replace the index The 'key value you applied for' in html is the applied key.

Application address of JSAPI developer key:

http://lbs.amap.com/ , click to open the link on the left and register the developer account in the upper right corner of the page to apply for a key.

Relevant reference websites:

Added by paulmo on Wed, 23 Feb 2022 14:21:34 +0200