preface

As a part-time job for programmers, the front-end development engineer 】 【 I developed applications often need to get the user location information, need to certain situations show map and map, some place, need to obtain a list of the administrative area (provinces), and address details information, need to plan a (dynamic) route on the map, track playback, mobile car, You need to create an information window for displaying summary information about a location.

Do is to share the project in the company, the scene is that sharing a common charging treasure (function almost like popular Shared cycling), was in a small program home page, need to do is scan code, contact customer service (feedback) problem, obtaining the geographical position, the opening is a geographical location, access to the area near your store information, Click the logo of the store to obtain the location of the store, business hours, store name, distance, whether there are currently available charging banks in the store and other information.

Sharing rechargeable electric vehicles 🚗, the home page is also a geographical location map, you can get the nearest shared electric vehicles near you, the vehicle address, status and other information. Display the car’s remaining battery, use records, lease orders, obtain travel track, mileage within a certain period of time, dynamic display track, etc.

In fact, there are a lot of sharing contents involved (such as electric cars, charging banks, but also renting equipment, etc.), but most of the functions are almost the same, need to pay deposit, rental fees, credit deposit free, etc. I have developed APPS, H5, Web sites and small programs that are closely related to location services related to maps. Let me tell you a story about location services.

The following is mainly about the map function and other functions, the use of Tencent position development services. Step by step, do some case shows, code instructions, use tutorials. (Note here I go back to see the development tutorial, try to be familiar with each function to explain how to use) 1, Tencent location service is what? Tencent location service is undoubtedly access to location services and other information content, the product highlights:

  1. Positioning: To provide perfect location solutions for partners and developers, has provided professional and accurate positioning services for social, travel, games, business, O2O, logistics and other fields
  2. Map: Tencent Location service provides rich map display forms for developers on multiple platforms, helping developers from different fields to easily build maps and build exclusive content on the basis of them. At the same time, with mass data, personalized customization, visualization and other capabilities to meet the needs of various industry scenarios for maps
  3. Location search: Based on massive live location (POI) data, provide peripheral search, city search, keyword input tips, classification and screening and other search capabilities, for social, logistics, travel and other industries to create exclusive search strategies, better experience
  4. Route planning: According to the departure point, destination and route strategy setting, combined with accurate real-time traffic conditions, we can provide driving, walking, cycling and bus route planning capabilities, helping developers to provide users with considerate and humanized travel experience
  5. Wechat small program solutions: Tencent position services fully embrace the small program ecology, from service API, basic map components, plug-ins, industry solutions and other levels of small program developers of different scene needs, help small program plug in the map “wings”!
  6. Personalized map: personalized style: thousands of lines and thousands of faces, help developers according to the use of their products, interface tone, select or create a matching style of map style, better experience; Personalized layer: real cool, help developers to generate map tiles from exquisite drawings and put them on the map, so that the display effect of tourist attractions, universities and other areas is different

Two, the use of steps

1. Description of UNIApp map development

Uniapp is used because it is a framework to develop all front-end applications using vue.js. Developers write a set of code, which can be published to ios, Android, Web and various small programs, quick applications and other platforms.

Use map map component development, map component used to display the map (use Tencent map), say its attributes are:

Longitude (type Number, no default value, longitude of the center) latitude (type Number, no default value, latitude of the center) scale (type Number, default value 16, longitude (type Number, no default value, longitude of the center) The zoom level ranges from 5 to 18. It is of the same type as an Array, which indicates that there are multiple markers on the map. Circles (type Array) controls (type Array) include-points (type Array) Enable-3d (type Boolean, default false, indicates whether 3D block is displayed) show-compass (type Boolean, default false, Enable -overlooking (type Boolean, default false, enable aerial view) enable-satellite (type Boolean, default false, Enable-traffic (type Boolean, default false, real-time traffic enabled) show-location (type Boolean, current registration point with direction displayed) Polygons (type Array, Represented as polygons)

Click properties

  1. @markertap- trigger when a marker is clicked, e.dot ={markerId}
  2. @labeltap- trigger when label is clicked, e.dot = {markerId}
  3. @callouttap- trigger when clicking the bubble corresponding to the mark point, e.dot = {markerId}
  4. Controltap – Triggered when a control is clicked, e.dot = {controlId}
  5. @regionChange – Trigger when the view changes
  6. @tap- trigger when clicking a map; App-nuve and wechat mini program 2.9 support returning latitude and longitude
  7. @updated- Fires when map rendering updates are complete

When we write the map component, the width/height of the component is recommended to write direct quantity, say 750rpx, do not set percentage value, only GCJ02 coordinate is supported in uni-app.

This topic describes the attributes that are of the Array type

It is an Array attribute that is used to display the location of markers on a map. The array property, which contains its object configuration properties, is:

  1. Id, marker POINT ID, type Number, mandatory, marker click event callback will return this ID, it is recommended to set Number type ID for each marker to ensure better performance when updating marker.
  2. Latitude, latitude, type Number, mandatory floating point Number, range of -90 to 90
  3. Longitude, type Number, mandatory, floating point Number, range from -180 to 180
  4. Title, callout, type String, not mandatory, display when clicked, ignored when callout exists
  5. IconPath, icon to display, type String, mandatory, image path in the project directory
  6. Rotate, rotation Angle, type Number, not mandatory. The value ranges from 0 to 360. The default value is 0
  7. Alpha, annotation transparency, type Number, not mandatory, default 1, no transparency, range 0 ~ 1
  8. Width, the icon width, type Number, not mandatory, default to the actual image width
  9. This parameter is optional. The default value is the actual height of the image
  10. Callout, bubble window above custom tag points, type Object, not mandatory – newline recognition
  11. Label, adds a label next to the label point, type Object, not mandatory – recognizes line breaks
  12. The anchor point of the annotation icon, the default bottom midpoint, not mandatory, {x, y}, x represents horizontal (0-1), y represents vertical (0-1). {x:.5, y: 1} represents the midpoint of the base

Bubbles on marker Callout (Object type) Attributes on marker array Callout objects use attributes:

  1. Content, text, String
  2. Color, text color, String
  3. FontSize, text size, Number
  4. BorderRadius, Callout rounded edges, Number
  5. BgColor, background color, String
  6. Padding, margin of text, Number
  7. Display, ‘BYCLICK’: click to display; ‘ALWAYS’: constant, String
  8. TextAlign, text alignment. Valid values: left, right, center, String

Marker label (Object type)

  1. Content, text, String
  2. Color, text color, String
  3. FontSize, text size, Number
  4. X, coordinate of label, origin is longitude and latitude corresponding to marker, Number
  5. Y, coordinate of label, origin is longitude and latitude corresponding to marker, Number
  6. BorderWidth, borderWidth, Number
  7. BorderColor, borderColor, String
  8. BorderRadius, rounded edges, Number
  9. BgColor, background color, String
  10. Padding, margin of text, Number
  11. TextAlign, text alignment. Valid values: left, right, center, String

polyline

Polyline specifies a series of coordinate points from the first entry to the last

  • Points, longitude and latitude Array, type Array, mandatory, e.g. [{latitude: 0, longitude: 0}]
  • Color, the color of the line, type String, need not fill, e.g. #0000AA
  • Width, the line width, type Number, do not need to fill
  • DottedLine, dotted or not, type Boolean, false by default
  • ArrowLine, the line with the arrow, type Boolean, do not need to fill in, default value is false
  • ArrowIconPath, replace the arrow icon. The type is String. If arrowLine is true, the arrow icon takes effect by default
  • BorderColor, the borderColor of the line, type String, no need to fill in
  • BorderWidth, the thickness of the line, type Number, no need to fill in

Polygon Polygon specifies a series of coordinates to generate a closed polygon based on the points coordinate data

  • Points, longitude and latitude array, array, mandatory, e.g. [{latitude: 0, longitude: 0}]
  • StrokeWidth, strokeWidth, Number, no
  • StrokeColor strokeColor, String, no
  • FillColor, fillColor, String, no
  • ZIndex, set the polygon z-axis value, Number, no

Circles Displays circles on a map

  • Latitude, latitude, Number, mandatory, floating point Number, range -90 to 90
  • Longitude Number mandatory floating point Number range between -180 and 180
  • Color, the color of the stroke, String, need not fill in, e.g. #0000AA
  • FillColor, fillColor, String, need not be filled, for example: #0000AA
  • Radius, radius, Number, mandatory
  • StrokeWidth, strokeWidth, Number, I don’t have to fill it in

Controls displays controls on a map that do not move with the map

  • Id, control ID, Number, not required, will be returned by the control click event callback
  • Position: the position of the control on the map. Object: The position of the control relative to the map
  • IconPath, the icon to display, String, mandatory, the image path under the project directory, supporting the relative path writing, start with ‘/’ represents the relative project root directory; Temporary paths are also supported
  • Clickable, clickable or not, Boolean, leave this blank, default is not clickable

position

  • Left, how far is it from the left edge of the map
  • Top, how far is it from the top edge of the map, Number, you don’t have to fill in, default is 0
  • Width, control width, Number, default image width
  • Height, control height, Number, left blank, default to image height

Note that the latitude and longitude of the map component in UNIapp must be filled in. If it is not filled in, the default value is the latitude and longitude of Beijing.

2. Uniapp uses the Map component

Basic usage

Use map component in UNIApp development, basic usage method: code is as follows (example) :

<map :scale="scale" style="width: 100%; height: 100%;"
enable-3D="false" show-compass="false" enable-overlooking="false"
:enable-satellite="false" :enable-traffic="false" show-location="false"
:latitude="latitude" :longitude="longitude" :markers="covers">
</map>
Copy the code

The following is an example of the markers used:

[{id: 1, // Number title: '1', // String- rotate: 180, // Number - rotate: 180, // Number - 0 ~ 1 latitude: 39.899, longitude: 116.39742, width: 30, height: 30, // callout: {// display: "BYCLICK", // padding: 10, // borderRadius: 5, // content: '', // }, // anchor: {}, iconPath: '.. /.. /.. / static/location. The PNG ', / / show the icon}, {id: 2, the title: '2', / / String latitude: 39.90, longitude: 116.39, the callout: {color: '#007AFF', // text color bgColor: '#563BFF', // background color display: "ALWAYS", // 'BYCLICK': ALWAYS display; 'ALWAYS': ALWAYS display fontSize: Valid values: left, right, Center padding: 10, // borderRadius: 5, Content: }, label: {content: 'Jeskson', color: '#000000', fontSize: 12, borderWidth: 12, borderColor: '#007AFF', borderRadius: 5, padding: 5, textAlign: 'center', bgColor: '#563BFF', }, iconPath: '../../../static/location.png' }]Copy the code

The preview looks like this:

controls:[{
    // Displays controls on the map. Controls do not move along the map
    id: 1./ / the control id
	iconPath:'.. /.. /static/icon.png'.// Display the icon
	position: {// The position of the control on the map
	 left: 15.top: 15.width: 50.height: 50}}],Copy the code

Address search

Uni-app only supports GCJ02 coordinates

OBJECT parameter in uni.getLocation(OBJECT)

Gets the current location, speed. In wechat applets, when the user leaves the application, this interface cannot be invoked unless the background continuous location permission is applied. This interface can continue to be invoked when the user clicks “Show at the top of chat.”

OBJECT Parameter Description

  • Wgs84 returns GPS coordinates, gCJ02 returns office coordinates, which can be used for uni. OpenLocation coordinates. App platform AUtonavi SDK only supports gCJ02
  • If true is used to return altitude information, it will slow down the interface return speed because getting height requires higher accuracy
  • Geocode, Boolean, leave this blank, default false, whether to parse address information
  • The interface called the callback Function successfully. For details about the returned Function, see the description of returned parameters
  • The interface calls the failed callback Function
  • The callback Function that completes the interface call (executed on success or failure).

Return parameters for SUCCESS:

  • Latitude a floating point number in the range of -90 to 90
  • Longitude is a floating point number between -180 and 180. A negative number denotes longitude west
  • Speed floating point number in m/s
  • Accuracy means accuracy of position
  • Altitude, unit m
  • VerticalAccuracy, verticalAccuracy, unit m (Android not available, return 0)
  • HorizontalAccuracy, in m
  • Address, address information (only supported by App, need to set geocode to true)

Address Indicates the address information

  • Country, String, country, such as “China”, return undefined
  • Type, String, undefined if the name of the province is “Beijing”
  • City, String, the city name, such as “Beijing”, returns undefined
  • District, String, county name, for example, Chaoyang District, undefined if there is no district name
  • Street, String, street information, such as “Jiuxianqiao Road”, return undefined
  • StreetNum, String, obtains the street number information, such as “3”, returns undefined if there is no street number
  • PoiName: String POI information, for example, Electronics city. International electronic headquarters “, no return undefined
  • PostalCode, String, zip code, for example, 100016
  • CityCode, String, cityCode, such as “010”, return undefined

Uni. ChooseLocation (OBJECT) Opens the map and selects a location.

  • Latitude String latitude of destination
  • Longitude longitude of the target
  • Keyword, String, no need to fill, search keyword, only supported by App platform
  • Success, Function, mandatory
  • Fail, Function, do not need to fill
  • Complete, Function

Success Returns the following parameters:

  • Name: location name
  • Address, detailed address
  • Latitude, floating point number, range of -90~90, negative numbers represent southern latitude, using GCJ02 national Bureau of Measurement coordinate system.
  • Longitude is a floating point number in the range of -180~180. Negative numbers represent longitude in the West using gCJ02 coordinates.

The code is as follows (example) :

chooseLocation(e) { // Open the map and select the location
	uni.chooseLocation({
		success: res= > {
			console.log('Location name:' + res.name);
			console.log('Full Address:' + res.address);
			console.log('Latitude:' + res.latitude);
			console.log('Longitude:' + res.longitude);
			uni.getLocation({
				type: 'gcj02'.altitude:true.geocode:true.success: function(res) {
					console.log('Longitude of current position:' + res.longitude);
					console.log('Latitude of current position:'+ res.latitude); }});console.log(':' + res.address.slice(0, res.address.indexOf('province') + 1));
			console.log('the city: + res.address.slice(res.address.indexOf('province') + 1, res.address.indexOf('the city') + 1));
			console.log('area: + res.address.slice(res.address.indexOf('the city') + 1, res.address.indexOf('area') + 1));
			this.query.address = res.address;
			this.query.latitude = res.latitude;
			this.query.longitude = res.longitude;
			this.query.province = res.address.slice(0, res.address.indexOf('province') + 1)
			this.query.city = res.address.slice(res.address.indexOf('province') + 1, res.address.indexOf('the city') + 1)
			this.query.district = res.address.slice(res.address.indexOf('the city') + 1, res.address.indexOf('area') + 1)}}); },Copy the code

Preview effect:

Get nearby dynamic, point aggregation

Uni.getnetworktype (OBJECT) Obtains the network type.

Uni.createmapcontext (mapId,this) creates and returns a mapContext object. Under a custom component, the second parameter is passed to the component instance this to operate on the component within the component.

MapContext -mapContext is bound to a component using a mapId. You can operate the corresponding component using the mapContext.

This object has a list of methods:

  • GetCenterLocation OBJECT Gets the latitude and longitude of the center of the current map
  • MoveToLocation OBJECT To move the center of a map to the current location, this OBJECT must be used together with show-location of the map component
  • TranslateMarker OBJECT moves marker to drive painting
  • IncludePoints OBJECT Zoom view shows all latitude and longitude
  • GetRegion OBJECT Gets the view range of the current map
  • GetScale OBJECT gets the scale level of the current map
  • $getAppMap gets the native Map object Plus.maps.map

The OBJECT argument list for getCenterLocation

Res = {longitude: “longitude “, latitude:” latitude “}

MoveToLocation OBJECT parameter list – Optional

TranslateMarker OBJECT parameter list

  • MarkerId Number Specifies a marker
  • Destination Object Specifies the target point to which the marker is moved
  • AutoRotate Boolean Does not need to specify whether marker automatically rotates during movement
  • Rotate Number The rotation Angle of marker is not required
  • Duration Number Specifies the animation duration. The default value is 1000ms. Translation and rotation are calculated separately
  • AnimationEnd Function does not need to fill in the animationEnd callback Function
  • Fail Function does not need to be filled in to call the failed callback Function of the interface

The code is as follows (example) :

<view id="activeMap">
	<view @tap="activeMarker={}">
		<view class="page-body map-view" style="z-index: 1; position: relative;">
			<view class="page-section page-section-gap map-view">
				<map :markers="shops" id="map1" :show-location="true" :latitude="latitude" :longitude="longitude" @regionchange="regionChange"
				 @markertap="markerTap" @tap="activeMarker={}">
					<! -- @markerTap Triggered when a marker is clicked, e.dot = {markerId}-->
					<! -- @tap Triggered when clicking on a map -->
					<! -- @regionChange Trigger when view changes -->
				</map>
				<cover-image class="map-image" src=".. /static/address.png"></cover-image>
			</view>
		</view>
	</view>
</view>
Copy the code
regionChange() { // Retrieve the store after moving the map
	uni.createMapContext('map1'.this).getCenterLocation({
		success: res= > {
			console.log(res.latitude)
			console.log(res.longitude)
			this.shopTimeout = setTimeout(_= > {
				this.shops = [{
					address: 1 Xx Avenue, XXX District, Shantou City, Guangdong Province, China.distance: 122.end_time: "1".id: 2.latitude: "22.72078500009999".longitude: "114.36090200009999".shop: {
						iconPath: '/static/logo.png'.id: 3.latitude: "22.72078500009999".longitude: "114.36090200009999".height: 34.width: 34.shop: {return: 0}},return: 0.height: 34.width: 34.start_time: "1".store_name: "Samsung Hotel".iconPath: '/static/shop.png',}},500)},fail: res= > {
			uni.showModal({
				content: 'Failed to get location'.showCancel: false}}}})),Copy the code

Preview renderings are as follows:

Map people nearby

The code is as follows (example) :

list: [{
	id: 1264640.user_id: 335187.place: "Jeskson city".text: "dadaqianduan.cn".latitude: "27.267520".longitude: "111.727120".status: "normal".nickname: "dada".avatar: "https://image.aishencn.com/2020/10/20/002207441_40845724-user.jpg".distance: 13419}, {id: 1272720.user_id: 36950.place: "Dadaqianduan city".text: "dadaqianduan.cn".latitude: "27.257640".longitude: "111.747910".deletetime: null.status: "normal".nickname: "dadaqianduan".avatar: "https://image.aishencn.com/2020/04/09/004135379_37869100-user.jpg".distance: 27070}, {id: 1316740.user_id: 366172.place: "dadaqianduan.cn".text: "dadaqianduan.cn".images: "https://image.aishencn.com/2020/11/04/215134979_98197351-bbs.jpg".latitude: "27.257430".longitude: "111.732960".status: "normal".nickname: "dada".avatar: "https://image.aishencn.com/2020/11/04/182622730_98197351-user.venus/cache/ext/crop/1604518314542_jpg".distance: 27190.images_arr: ["https://image.aishencn.com/2020/11/04/215134979_98197351-bbs.jpg"]}],Copy the code

Preview effect is shown below:

Locate nearby stores

The code is as follows (example) :

// The distance between two points
distance(la1, lo1, la2, lo2) {
	var La1 = (la1 * Math.PI) / 180.0
	var La2 = (la2 * Math.PI) / 180.0
	var La3 = La1 - La2
	var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0
	var s =
		2 *
		Math.asin(
			Math.sqrt(
				Math.pow(Math.sin(La3 / 2), 2) +
				Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)
			)
		)
	s = s * 6378.137 // Radius of the earth
	s = Math.round(s * 10000) / 10000
	return s
},
// Calculate the nearest distance
nearDistance(array, centerLatitude, centerLongitude) {
	let temp = []
	for (let i = 0, l = array.length; i < l; i++) {
		const element = array[i]
		let d = this.distance(
			element.latitude,
			element.longitude,
			centerLatitude,
			centerLongitude
		)
		temp.push(d)
	}
	this.distanceL = Math.min.apply(null, temp)
}
Copy the code

The effect is shown below:

Sliding track

The code is as follows (example) :

<map :polyline="polyline" :scale="scale" id="maps" :markers="markers" :latitude="center.latitude"
:longitude="center.longitude">
</map>
Copy the code
// Play the marker
playMarkars() {
	if (this.polyline.length == 0) {
		uni.showModal({
			content: 'There is no track in the current time range, cannot play! ',})this.isPlay = false / / no
		this.playIndex = 0 / / the first
		return
	}
	this.playIndex = Math.min(this.points.length - 1.this.playIndex)
	this.markers = [this.formatMarker(this.points[this.playIndex++], 'ALWAYS')]
	this.timer = setInterval(_= > {
		var i = this.playIndex++
		this.nextAdaress(i);
		if (i >= this.points.length) {
			clearInterval(this.timer)
			this.isPlay = false
			this.playIndex = 0
			this.initMarkers()
			return
		}
		this.markers = [this.formatMarker(this.points[i], 'ALWAYS')]},1000)},formatMarker(point, display = "BYCLICK") {
	let content = [
		"Time:" + parseTime(point.create_time),
		"State of motion:" + (point.sport == 1 ? 'movement' : 'static'),
		"Address:" + point.address || ' '
	]
	return {
		id: point.id,
		iconPath: '/static/dada.png'.width: 35.height: 35.latitude: point.latitude,
		longitude: point.longitude,
		callout: {
			display: display,
			padding: 10.borderRadius: 5.content: content.join("\n")}}},nextAdaress(index) {
	const len = 10;
	if (this.isGetAddress) {
		return
	}
	for (let i = 0; i < len; i++) {
		if (!this.points[i + index]) {
			break
		}
		if (this.points[i + index].address === undefined) {
			this.isGetAddress = true
			this.getAddress(i + index, len * 2._= > {
				this.isGetAddress = false
			});
			break}}},Copy the code

The image looks like this:

Vue access Tencent map interface

Tencent (Recommended)

https://apis.map.qq.com/ws/location/v1/ip={$ip}&key={$key}
Copy the code

Need to apply for key, fast, with basic information

Click on the home page to register and apply for a key:Key management: Create a new key and fill in the corresponding information1. Create map preview renderings as follows:

<script charset="utf-8" src="The key https://map.qq.com/api/gljs?v=1.exp&key= application"></script>

 <script type="text/javascript">
    function initMap() {
        var center = new TMap.LatLng(39.984104.116.307503);
        // Initialize the map
        var map = new TMap.Map("container", {
            rotation: 20.// Set the map rotation Angle
            pitch:30.// Set pitch Angle (0~45)
            zoom:12.// Set the map zoom level
            center: center// Set the map center coordinates
        });
    }
</script>
Copy the code

2. Renderings of completed map loading:

<script>
    function initMap() {
        // Initialize the map
        var map = new TMap.Map("container", {
            center: new TMap.LatLng(39.984104.116.307503)});// Listen for the map tile loading completion event
        map.on("tilesloaded".function () {
            document.getElementById("tip").innerHTML = "Map tiles are loaded."
        })
    }
</script>
Copy the code

3. Asynchronously load the map

<script>
        function initMap() {
            var map = new TMap.Map("container", {
                pitch: 45.zoom: 12.center: new TMap.LatLng(39.984104.116.307503)}); }function loadScript() {
            // Create a script tag and add the SRC attribute to the body
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "The key https://map.qq.com/api/gljs?v=1.exp&key= application";
            document.body.appendChild(script);
        }
        window.onload = loadScript;
    </script>
Copy the code

4. Loading two map renderings at the same time:

<script>
    function initMap() {
        // Initialize map 1
        var mapOne = new TMap.Map("containerOne", {
            pitch:45.center: new TMap.LatLng(39.984104.116.307503)});// Initialize map 2
        var mapTwo = new TMap.Map("containerTwo", {
            center: new TMap.LatLng(39.984104.116.307503)}); } </script>Copy the code

5. Get the center effect of the map as shown below:

<script>
    var centerInfo = document.getElementById("center-info");

    var center = new TMap.LatLng(39.984104.116.307503);// Set the center coordinates
    // Initialize the map
    var map = new TMap.Map("container", {
        center: center
    });
    // Get the map center point event
    function getCenter() {            
        var mapCenter = map.getCenter(); // Get the center coordinates of the map
        centerInfo.innerHTML = "Current map center is:" + mapCenter.getLat().toFixed(6) + "," + mapCenter.getLng().toFixed(6);
    }
    // Set the map center point event
    function setCenter() {
        map.setCenter(new TMap.LatLng(39.908802.116.397502));// The coordinate is Tian 'anmen
        centerInfo.innerHTML = "Current map center: 39.908802,116.397502";
    }
</script>
Copy the code

6. The translation effect of the map is as follows:

<script>
    function initMap() {
        var position = document.getElementById("position");
        var txt = document.getElementById("txt");
        var center = new TMap.LatLng(39.984104.116.307503);// Set the center coordinates
        // Initialize the map
        var map = new TMap.Map("container", {
            center: center
        });
        location.innerHTML = map.getCenter().toString();
        // Listen to the map start panning
        map.on("panstart".function () {
            txt.innerHTML = "The map starts to shift."
        })
        // Listen for map pan
        map.on("pan".function(){
            txt.innerHTML = "The map is shifting.";
            position.innerHTML = map.getCenter().toString();// Get the center of the map
        })
        // Listen to map panning end
        map.on("panend".function(){
            txt.innerHTML = "End of map pan";
        })
    }
</script>
Copy the code

3. Vue is connected to Tencent Map

<template>
  <div>
    <div id="map" style="width:500px; height:500px;"></div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      longitude: "".latitude: ""
    };
  },
  
  methods: {
    init() {
      let address = "";
      let that = this;
      var center = new qq.maps.LatLng(34.754152.113.667636);
      var map = new qq.maps.Map(document.getElementById('map'), {
        center: center,
        zoom: 13.disableDefaultUI: true
      });
      var marker = new qq.maps.Marker({
        position: center,
        map: map
      });
      var infoWin = new qq.maps.InfoWindow({
        map: map
      });
      var geocoder = new qq.maps.Geocoder({
        complete: function(res) {
          console.log(res);
          address = res.detail.nearPois[0].name; }}); qq.maps.event.addListener(map,"click".function(event) {
        this.longitude = event.latLng.getLat();
        this.latitude = event.latLng.getLng();
        console.log(event);
        let lat = new qq.maps.LatLng(this.longitude, this.latitude);
        geocoder.getAddress(lat);
        setTimeout(() = > {
          infoWin.open();
          infoWin.setContent(
            '
        
'
+ address + "</div>" ); infoWin.setPosition(event.latLng); }, 200); }); }},mounted() { this.init(); }};
</script>
<style scoped> </style> Copy the code

To use the map, you need to import it in index.html.

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=yourkey"></script>
<template>
    <div>
        <div id="container" style="width:500px; height:500px;"></div>
    </div>
</template>

<script>
    export default{
    	data() {
            return {
                longitude:39.956987./ / longitude
                latitude:116.235128 / / latitude
            }
        },
        mounted () {
            this.init();
        },
        methods: {init() {
                var myLatlng = new qq.maps.LatLng(39.945687.116.3976968);
                var myOptions = {
                  zoom: 8.// Set the map zoom level
                  center: myLatlng,      // Set the center point style
                  mapTypeId: qq.maps.MapTypeId.ROADMAP   
                }
                var map = new qq.maps.Map(document.getElementById("container"), myOptions); }}}</script>
Copy the code

Creating a map instance

var map=new qq.maps.Map(document.getElement('container'),{
center,// Coordinates, the center of the map originally displayed
zoom    // Zoom level, which is the scale of the display})Copy the code

Add events to the map

qq.maps.event.addListener(map,'click'.function(res){
// res is the location of the click
})
Copy the code

Add tag

var marker=new qq.maps.Marker({
position, // Mark the position of the point, also can be obtained by IP coordinates
map, // Which map is marked on
animation, // Animate the display of the tag
title, // The title when the mouse hovers over the tag
draggable // Whether it can be dragged
})
Copy the code

Create information window

var info=new qq.maps.InfoWindow({
map, // Which map is marked on
content // The contents of the info window
})
Copy the code

mulch

var polyline=new qq.maps.Polyline({
map, // Which map is marked on
path, // An array of coordinates from which polygons and polygons are formed
strokeColor, // Fold color
strokeDashStyle, // A line style
strokeWeight, // Fold width
editable, // Whether the folds are editable
clickable // Is it clickable
})
Copy the code

Single label point

Call the initialization map method after the Mounted life cycle or after getting information from the background interface

initMap (latitude, longitude, message) {
    var center = new qq.maps.LatLng(latitude, longitude);
    var map = new qq.maps.Map(
        document.getElementById("container"),
        {
            center: center,
            zoom: 13});var marker = new qq.maps.Marker({
        position: center,
        map: map
    });

    var info = new qq.maps.InfoWindow({
        map: map
    });
    
    // The floating flag displays information
    qq.maps.event.addListener(marker, 'mouseover'.function() {        
        info.open();
        info.setContent(`<div style="margin:10px;" >${message}</div>`);
        info.setPosition(center);
    });
    qq.maps.event.addListener(marker, 'mouseout'.function() {
        info.close();
    });
},
Copy the code

Multiple annotation points

markers: [  ]; // mark the points group

mounted () {
    this.initMap(this.markers)
},

initMap (arr) {
    // The default is to center on the first item of the array
    var center = new qq.maps.LatLng(arr[0].latitude, arr[0].longitude);
    
    var map = new qq.maps.Map(
        document.getElementById("container"),
        {
            center: center,
            zoom: 13});/ / hint window
    var info = new qq.maps.InfoWindow({
        map: map
    });
    
    for (var i = 0; i < arr.length; i++) {
        var data = arr[i];

        var marker = new qq.maps.Marker({ 
            position: new qq.maps.LatLng(data.latitude, data.longitude), 
            map: map 
        });

        marker.id = data.id;
        marker.name = data.name;
        // Click the event
        qq.maps.event.addListener(marker, 'mouseover'.function() {
            info.open();
            // Set the prompt window content
            info.setContent(`<div><p>The ${this.name}</p></div>`);
            // Prompt window position
            info.setPosition(new qq.maps.LatLng(this.position.lat, this.position.lng));
        });
        qq.maps.event.addListener(marker, 'mouseout'.function() { info.close(); }); }}Copy the code

4. Personalize the map style

Why should we use personalized maps to improve the display effect and user experience of maps in different scenes?Why choose Tencent Location service personalized map:

  • Universal platform
  • Minimal development costs
  • Personalized styles support dynamic updates
  • Supports global configuration and hierarchical configuration
  • Edit platform UI controls are fully optimized
  • All configurable attributes for each element are open
  • Support for custom map elements expanded to 52

5. Steps to get started on Tencent location

1. Log in to Tencent location service

Verify your mobile phone and email address. 3. Apply for a development Key

Location display componentRoute planning componentMap selection componentFront-end positioning assembly

Iii. Wechat small program JavaScript SDK

1. I have applied for the developer key. 2. Console -> Key Management -> Settings (key using this function) -> Select webserviceAPI -> Save (the small program SDK needs to use some services of webserviceAPI, so the key using this function needs to have corresponding permissions) 10000 times/Key—- Number of concurrent requests: 5 times/Key/second.

onLoad() {
	console.log('Page loaded')
	// Instantiate the API core class
	qqmapsdk = new QQMapWX({
		// key: 'request key'
	});
},
onShow() {
	console.log('Page displayed')
	// Invoke interface dadaqianduan
	qqmapsdk.search({
		keyword: 'hotel'.success: (res) = > {
			console.log(res);
		},
		fail: (err) = > {
			console.log(err);
		},
		complete: (cres) = > {
			console.log(cres); }})},Copy the code

The data I returned is shown below:QQMapWX – Small Program JavaScriptSDK core class – new QQMapWX(Options :Object)

// Introduce SDK core classes
var QQMapWX = require('xxx/qqmap-wx.js');
 
// Instantiate the API core class
var demo = new QQMapWX({
    key: 'Develop key' / / required
});
Copy the code

Location search:

// Location search
nearbySearchBtn() {
	qqmapsdk.search({
		keyword: 'kfc'.// Search for keywords
		location: 39.980014 ', 116.313972 '.// Set the peripheral search center point
		success: (res) = > {
			var mks = []
			for (var i = 0; i < res.data.length; i++) {
				mks.push({ // Get the result and place it in the MKS array
					title: res.data[i].title,
					id: res.data[i].id,
					latitude: res.data[i].location.lat,
					longitude: res.data[i].location.lng,
					iconPath: "/location.png".// Icon path
					width: 20.height: 20})}this.markers = mks
		},
		fail: (res) = > {
			console.log(res);
		},
		complete: (res) = > {
			console.log(res); }}); },Copy the code

The effect is as follows:

<script>
	// Introduce SDK core classes, js files according to their own business, location can be placed by themselves
	// var QQMapWX = require('.. /.. /js_sdk/wxmp-qqmap/qqmap-wx-jssdk.js');
	import QQMapWX from '.. /.. /js_sdk/wxmp-qqmap/qqmap-wx-jssdk.js';
	var qqmapsdk;
	export default {
		components: {},
		data() {
			return {
				backfill: ' '.markers: [].suggestion: [].}},onLoad() {
			console.log('Page loaded') // Instantiate the API core class
			qqmapsdk = new QQMapWX({ // key: 'request key'
				key: 'Apply yourself, and mine won't be released.'
			});
		},
		onShow() {
			console.log('Page displayed') // Invoke interface dadaqianduan
			qqmapsdk.search({
				keyword: 'hotel'.success: (res) = > {
					console.log(res);
				},
				fail: (err) = > {
					console.log(err);
				},
				complete: (cres) = > {
					console.log(cres); }})},onReady() {
			console.log('Page rendered for the first time')},methods: {
			getsuggest(e) {
				console.log(e.detail.value)
			    qqmapsdk.getSuggestion({
			      keyword: e.detail.value, // Fixed values can be set for user input keywords, such as keyword:'KFC'
			      //region:' Beijing ', // Set the city name, limit the region shown in the keyword, optional parameter
			      success: (res) = > {// Callback after successful search
			        console.log(res);
			        var sug = [];
			        for (var i = 0; i < res.data.length; i++) {
			          sug.push({ // Get the result and place it in the sug array
			            title: res.data[i].title,
			            id: res.data[i].id,
			            addr: res.data[i].address,
			            city: res.data[i].city,
			            district: res.data[i].district,
			            latitude: res.data[i].location.lat,
			            longitude: res.data[i].location.lng
			          });
			        }
			         this.suggestion = sug
			      },
			      fail: (error) = > {
			        console.error(error);
			      },
			      complete: (res) = > {
			        console.log(res); }}); },backfillBtn(e) {
				var id = e.currentTarget.id;
				for (var i = 0; i < this.suggestion.length; i++) {
					if (i == id) {
						this.backfill = this.suggestion[i].title
					}
				}
			},
			// Location search
			nearbySearchBtn() {
				qqmapsdk.search({
					keyword: 'kfc'.// Search for keywords
					location: 39.980014 ', 116.313972 '.// Set the peripheral search center point
					success: (res) = > {
						var mks = []
						for (var i = 0; i < res.data.length; i++) {
							mks.push({ // Get the result and place it in the MKS array
								title: res.data[i].title,
								id: res.data[i].id,
								latitude: res.data[i].location.lat,
								longitude: res.data[i].location.lng,
								iconPath: "/static/location.png".// Icon path
								width: 20.height: 20})}this.markers = mks
					},
					fail: (res) = > {
						console.log(res);
					},
					complete: (res) = > {
						console.log(res); }}); }},onHide() {
			console.log('Page hidden')
		},
	}
</script>
Copy the code

The preview effect is shown below:

<script>
	import QQMapWX from '.. /.. /js_sdk/wxmp-qqmap/qqmap-wx-jssdk.js';
	var qqmapsdk;
	export default {
		components: {},
		data() {
			return {
				backfill: ' '.markers: [].poi: {
					latitude: 39.984060.longitude: 16.307520}}},onLoad() {
			console.log('Page loaded') // Instantiate the API core class
			qqmapsdk = new QQMapWX({ // key: 'request key'
				key: ' '
			});
		},
		onShow() {
			console.log('Page displayed')},onReady() {
			console.log('Page rendered for the first time')},methods: {
			formSubmit(e) {
				qqmapsdk.reverseGeocoder({
					location: e.detail.value.reverseGeo || ' '.// Get the coordinates of the position passed into the form
					//get_poi: 1, // Whether to return the list of surrounding POIS: 1. Return; 0 does not return (default), non-mandatory argument
					success: (res) = > {
						console.log(res);
						var res = res.result;
						var mks = [];
						/** * if get_poi = 1, select * for (var I = 0; i < result.pois.length; Id: result.pois[I]. Id: result.pois[I]. Id, latitude: result.pois[i].location.lat, longitude: result.pois[i].location.lng, iconPath: '. / resources/placeholder. PNG ', / / icon path width: 20, height: 20})} * * * /
						// When get_poi is 0 or the default value is not specified, the target location is retrieved as required
						mks.push({ // Get the result and place it in the MKS array
							title: res.address,
							id: 0.latitude: res.location.lat,
							longitude: res.location.lng,
							iconPath: '/static/location.png'.// Icon path
							width: 20.height: 20.callout: { // Displays the address name on the markers, as required or not
								content: res.address,
								color: '# 000'.display: 'ALWAYS'}});this.markers = mks;
						// this.poi = {
						// latitude: res.location.lat,
						// longitude: res.location.lng
						// }
					},
					fail: (error) = > {
						console.error(error);
					},
					complete: (res) = > {
						console.log(res); }}}}),onHide() {
			console.log('Page hidden')
		},
	}
</script>
Copy the code

Geocoder – Provides conversion from address description to location coordinates, the reverse of the reverse address resolution reverseGeocoder() process. Preview effect is shown below:

formSubmit(e) {
    // Call the address resolution interface
    qqmapsdk.geocoder({
      // Get the form's incoming address e.daile.value.geocoder
      address: e.detail.value, // Fixed address: '74 Haidian West Street, Caihefang Road, Haidian District, Beijing'
      success: (res) = > {// Successful callback
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        // Mark the address location on the map according to address resolution
         this.markers = [{
            id: 0.title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '/static/location.png'.// Icon path
            width: 20.height: 20.callout: { // The latitude and longitude can be displayed as required
              content: latitude + ', ' + longitude,
              color: '# 000'.display: 'ALWAYS'}}].this.poi= { // Set the corresponding map center coordinate variable name according to your own data
            latitude: Number(latitude),
            longitude:  Number(longitude),
          }
      },
      fail: (error) = > {
        console.error(error);
      },
      complete: (res) = > {
        console.log(res); }})}Copy the code

Preview renderings are as follows:

formSubmit(e){
	    // Call the distance calculation interface
		console.log(this.start,'dadaqianduan')
	    qqmapsdk.calculateDistance({
	        //mode: 'driving',// Optional values: 'driving', 'walking', default: 'walking', optional
	        // The from parameter does not contain the default current address
	        // Get the latitude and longitude of the form submission and set the FROM and to arguments (in string format for example)
	        / / the from: e.d etail. Value. Start | | ', / / if the starting point starting point coordinate data is used, if the default current address is empty
			from: this.start || ' '.to: this.end,
	        // to: e.daile.value. dest, //
	        success: (res) = > {// Successful callback
	          console.log(res);
	          var res = res.result;
	          var dis = [];
	          for (var i = 0; i < res.elements.length; i++) {
	            dis.push(res.elements[i].distance); // Store the returned data into the dis array,
	          }
	          this.distance=dis
	        },
	        fail: (error) = > {
	          console.error(error);
	        },
	        complete: (res) = > {
	          console.log(res); }}); }},Copy the code

Call the interface to get the city list, the effect picture is as follows:

onShow() {
	console.log('Page displayed')
	// Call the get city list interface
	qqmapsdk.getCityList({
		success: (res) = > { // Successful callback
			console.log(res);
			console.log('Province data:', res.result[0]); // Prints the province data
			this.a = res.result[0]
			console.log('City Data:', res.result[1]); // Print city data
			this.b = res.result[1]
			console.log(District/County Data:, res.result[2]); // Print district data
			this.c = res.result[2]},fail: (error) = > {
			console.error(error);
		},
		complete: (res) = > {
			console.log(res); }}); },Copy the code

Obtain the city districts and counties, the renderings are as follows:

onShow() {
	console.log('Page displayed')
	// Call the get city list interface
	qqmapsdk.getCityList({
		success: (res) = > { // Successful callback
			console.log(res);
			console.log('Province data:', res.result[0])
			var city = res.result[0];
			// Get district/county data according to the Id of the data returned by the corresponding interface getCityList (take Beijing as an example)
			qqmapsdk.getDistrictByCityId({
				// Pass in the province ID to get the city data, pass in the city ID to get the district data, and so on
				id: city[0].id, // getCityList returns the Id of the data, e.g. Beijing is '110000'
				success: (res) = > { // Successful callback
					console.log(res);
					console.log('District/county data under the corresponding city ID (take Beijing as an example) :', res.result[0]);
				},
				fail: (error) = > {
					console.error(error);
				},
				complete: (res) = > {
					console.log(res); }}); },fail: (error) = > {
			console.error(error);
		},
		complete: (res) = > {
			console.log(res); }}); },Copy the code

Tencent location service provides basic punctuation ability, line and circle drawing interface and other map components and location display, map selection and other map API location service ability support for wechat mini program, so that developers can freely realize their own wechat mini program products. Based on this, tencent location service WeChat applet JavaScript SDK is designed for small developers LBS data service provided by the toolkit, can be in a small program called tencent POI location service retrieval, input keywords, address resolution and reverse address resolution, administrative division and distance calculation data services, such as the small program allows you to more powerful!

Original author: Programmer Doraemon original link: blog.csdn.net/qq_36232611…