Recently, my company is working on a project of shared electric vehicles. When I open the app, I will see a map, which can obtain the address and status of nearby shared electric vehicles. To develop the app, I also need to plan the route on the map, dynamically display the trajectory, and replay the trajectory. The project functions of shared development always use LBS (Location Based Service), that is, location-based Service. There are Baidu Map, Autonavi Map and Tencent Map providing map services in China. In this paper, Tencent Location Service is selected to develop map functions.

Two, the use of steps

1. Description of UNIApp development Map

I use UniApp because it is a framework for developing all front-end applications using Vue.js. Developers write a set of code that can be published to ios, Android, web and various small programs, fast applications and other platforms.

The map component is used to display the map (when used by Tencent map). It has the following properties:

Longitude (type Number) Latitude (type Number) Latitude (type Number) Scale (type Number, default value is 16, Scale level Ranges from 5 to 18) Markers (Array indicates that there are multiple markers on the map) Polyline (Array indicates that there is no default value) Lines (polyline indicates that there is no default value) All the points on an Array are lined up. (Circles) Controls (controls) include (points) Enable -3D (type Boolean, default value is false, indicates whether to display 3D blocks) show-compass (type Boolean, default value is false, Enable-overlooking (The type is Boolean, the default value is false, indicating whether to enable overlooking) enable-satellite (the type is Boolean, the default value is false, Enable-traffic (The type is Boolean, and the default value is false, indicating whether to enable real-time traffic) show-location (the type is Boolean, indicating that the current registration point with direction is displayed) polygons (the type is Array, Represented as polygons)

Click properties

  1. @markertap- triggers when a marker is clicked, e.trace ={markerId}
  2. @labelTAP – triggers when label is clicked, e.trace = {markerId}
  3. @callouttap- trigger when clicking on the bubble corresponding to the marked point, e.trace = {markerId}
  4. @controlTap – means triggered when the control is clicked, e.trace = {controlId}
  5. @ Regionchange – triggered when the view changes
  6. @tap- triggers when a map is clicked; App-nuve, wechat small program 2.9 support to return latitude and longitude
  7. @updated- triggered when the map rendering update is complete

When we write the Map component, it is recommended to write the width/height of the component directly, such as 750rpx. Do not set the percentage value. In uni-app, only the gCJ02 coordinates are supported.

Describes the markers attribute. – The type is Array

The markers attribute type is Array, indicating that the markers are used to display the locations of markers on a map. This array property, which contains its object configuration properties, is:

  1. The marker click event callback will return this ID. It is suggested to set the type ID of Number for each marker to ensure better performance when updating the marker.
  2. Latitude, latitude, type Number, a mandatory floating point Number. The value ranges from -90 to 90
  3. Longitude, type Number, mandatory, floating point Number, range -180 to 180
  4. Title, callout, type String, not mandatory, displayed when clicked, callout will be ignored if it exists
  5. IconPath, icon displayed, type String, mandatory, picture path in the project directory
  6. Rotate, the rotation Angle, type Number, is not mandatory. The value ranges from 0 to 360. The default value is 0
  7. Alpha, opacity of annotations, type Number, not required, default 1, no transparency, range 0 ~ 1
  8. Width, annotated icon width, type Number, not required, default is the actual image width
  9. < font style = “font-size: 14px;
  10. Callout, the bubble window above the custom marker, type Object, is not required – recognisable newlines
  11. Label, adds a label next to the tag point, type Object, not required – recognizable newline character
  12. Longitude and latitude are in the anchor point of the annotated icon, default bottom midpoint, not required, {x, y}, x means landscape (0-1), y means vertical (0-1). {x:.5, y: 1} represents the midpoint of the bottom edge

Marker bubble Callout (Object type) Marker array attribute Callout objects use attributes:

  1. Content, text, String
  2. Color, text color, String
  3. FontSize, text size, Number
  4. BorderRadius, Callout border rounded, Number
  5. BgColor, background color, String
  6. Padding, white space at the edge of the text, Number
  7. Display, ‘BYCLICK’: click to display; ‘ALWAYS’: often displayed, String
  8. TextAlign, text alignment. Valid values: left, right, center, String

Label (Object type) on Marker

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

polyline

Polyline specifies a series of coordinate points, from the first to the last item in the array

  • Points, Array of longitude and latitude, mandatory, for example: [{latitude: 0, longitude: 0}]
  • < span style = “box-sizing: border-box; color: line color; type String
  • Width, the width of the line, type Number, do not need to fill
  • DottedLine: whether the line is dotted or not. The type is Boolean. No need to fill in
  • ArrowLine, the line with an arrow, type Boolean, no need to fill, default is false
  • ArrowIconPath, replace the arrow icon, type String, do not need to fill, when arrowLine is true, the default line with arrow
  • BorderColor: border-color of type String
  • BorderWidth: Thickness of line, type Number, not required

Polygon A polygon specifies a set of coordinate points from which a closed polygon is generated

  • [{latitude: 0, longitude: 0}]
  • StrokeWidth, strokeWidth, Number, no
  • StrokeColor Color of stroke, String, no
  • FillColor, fillColor, String, no
  • ZIndex: set the value of the polygon’s z-axis, Number, no

Circles Circles displays circles on a map

  • Latitude, latitude, and Number are mandatory floating point numbers ranging from -90 to 90
  • This parameter is mandatory. It is a floating point Number ranging from -180 to 180
  • Color, stroke color, String, do not fill, for example: #0000AA
  • FillColor, String, do not need to fill, such as #0000AA
  • Radius, radius, Number, mandatory
  • StrokeWidth, the width of the stroke, Number, do not need to be filled

Controls Displays controls on the map. Controls do not move with the map

  • Id, control ID, Number, do not need to fill in, the control click event callback will return this ID
  • Position, the position of the control on the map, Object, required, the position of the control relative to the map
  • IconPath, icon displayed, String, mandatory, image path in the project directory, support relative path writing, start with ‘/’ indicates relative project root directory; Temporary paths are also supported
  • Clickable, whether clickable, Boolean, do not have to fill, default is not clickable

position

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

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

2. Uniapp uses the Map component

Basic usage

Use uniAPP to develop the map component, the basic use method: the 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 code for using the markers attribute is as follows:

Rotate: [{id: 1, // Number title: '1', // String- rotate: 180, // Number - rotate: 180 alpha: [{id: 1, // Number title: '1'] 0.5, // Default 1, no transparency, range 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', // color: '#563BFF', // color: '#563BFF', // color: '#563BFF', // color: '#563BFF', // color: '#563BFF' Valid values: left, right, center padding: 10, // Text-padding 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 the control on the map. The control does not move with the map
    id: 1./ / the control id
	iconPath:'.. /.. /static/icon.png'.// Display the icon
	position: {// The location 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

The OBJECT parameter in uni.getLocation(OBJECT)

Get the current geographic location, speed. In wechat small program, when the user leaves the application, this interface cannot be called, unless the background continuous location permission is applied; This interface continues to be called when the user clicks “Show at the top of chat”.

OBJECT Parameter Description

  • Type, String, do not need to fill, default is WGS84 returns GPS coordinates, gCJ02 returns national survey office coordinates, can be used for uni. OpenLocation coordinates, app platform Autaud SDK only support to return GCJ02
  • Altitude, Boolean, do not need to fill, passing true will return altitude information, because the high accuracy required to get altitude will slow down the interface return speed
  • Geocode, Boolean, not required, default false, whether to resolve address information
  • Success, Function, mandatory. The callback Function is successfully called by the interface. See the return parameter description for details
  • Fail, Function, do not need to fill, interface call failed callback Function
  • The callback Function that completes the call to the interface (executing on success or failure)

For SUCCESS, the following parameters are returned:

  • Floating point number ranging from -90 to 90, with negative numbers indicating latitude south
  • Longitude is a floating point number ranging from -180 to 180. A negative number indicates longitude west
  • Speed, speed, floating point number, unit: m/s
  • Accuracy c
  • Altitude m
  • VerticalAccuracy, in m (not available on Android, return 0)
  • HorizontalAccuracy, in m
  • Address: address information (only supported by the App. Set Geocode to true)

Address Indicates the address information

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

Uni. ChooseLocation (OBJECT) Opens the map and selects the position.

  • Latitude, String, you don’t need latitude of the destination
  • It’s a longitude String, it doesn’t have to be the longitude of the target
  • Keyword, String, do not need to fill, search keyword, only App platform support
  • Success, Function, required
  • Fail, Function, not required
  • Complete, Function, not required

Success Returns the following parameters:

  • Name, the name of the location
  • Address, detailed address
  • Floating point number ranging from -90 to 90. Negative numbers indicate latitude in the south. Use the GCJ02 National Survey Bureau coordinate system.
  • Longitude is a floating point number ranging from -180 to 180. A negative number is longitude longitude west. Use the GCJ02 national Survey bureau coordinate system.

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('Detailed 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 at 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 dynamic near point aggregation

Uni.getnetworktype (OBJECT) Gets the network type.

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

MapContext – A mapContext is bound to a component by a mapId. It can be used to operate the corresponding component.

This object has a list of methods:

  • GetCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT getCenterLocation OBJECT
  • MoveToLocation OBJECT Moves the center of the map to the current registration point. This parameter is used together with the show-location of the Map component
  • TranslateMarker OBJECT translation marker to drive the painting
  • IncludePoints OBJECT Zoom view shows all latitude and longitude
  • The getRegion OBJECT gets the view range of the current map
  • GetScale OBJECT Gets the zoom level of the current map
  • $getAppMap Gets the native Map object plus. Maps.map

GetCenterLocation OBJECT parameter list

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

MoveToLocation OBJECT parameter list – do not need to fill

TranslateMarker OBJECT parameter list

  • MarkerId Number Specifies marker
  • Destination Object Specifies the target point to which the marker moves
  • AutoRotate Boolean Does not need to fill in whether marker is automatically rotated during movement
  • Rotate Number Does not need to fill in the rotation Angle of marker
  • Duration Number Specifies the duration of the animation. The default value is 1000ms. Translation and rotation are calculated separately
  • AnimationEnd Function do not need to fill in the animationEnd callback Function
  • Fail Function Does not need to fill in the callback Function when the interface fails to call

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 Triggers when a marker is clicked, e.Trace = {markerId}-->
					<! -- @tap Triggers when a map is clicked -->
					<! -- triggered when @regionChange visual field changes -->
				</map>
				<cover-image class="map-image" src=".. /static/address.png"></cover-image>
			</view>
		</view>
	</view>
</view>
Copy the code
regionChange() { // Reacquire 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.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

The preview is as follows:

The map shows people who are 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

The preview effect is shown as follows:

Locating nearby stores

The code is as follows (example) :

// 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 as follows:

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: 'No tracks in 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 to 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, speed, 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 the map preview 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 the pitch Angle (0~45)
            zoom:12.// Set the map zoom level
            center: center// Set the map center point coordinates
        });
    }
</script>
Copy the code

2. Map loading completed effect drawing:

<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 completed event
        map.on("tilesloaded".function () {
            document.getElementById("tip").innerHTML = "Map tiles loaded"
        })
    }
</script>
Copy the code

3. Load the map asynchronously

<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. Simultaneous loading of two map renderings is as follows:

<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 map center effect 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
    });
    // Retrieve the map center event
    function getCenter() {            
        var mapCenter = map.getCenter(); // Get the map center coordinates
        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 for the map to shift
        map.on("panstart".function () {
            txt.innerHTML = "The map begins to shift"
        })
        // Listen for map translation
        map.on("pan".function(){
            txt.innerHTML = "The map is shifting";
            position.innerHTML = map.getCenter().toString();// Get the center of the map
        })
        // Listen for the end of map translation
        map.on("panend".function(){
            txt.innerHTML = "Map ends translation";
        })
    }
</script>
Copy the code

3. Vue access 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,// The coordinate is the center of the map initially displayed
zoom    // The scale level 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 information after clicking
})
Copy the code

Add tag

var marker=new qq.maps.Marker({
position, // Mark the location of the point, which can also be the coordinates obtained through IP
map, // Which map to mark
animation, // The animation effect when the tag is displayed
title, // The title when the mouse hovers over the tag
draggable // Whether to drag
})
Copy the code

Create information window

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

mulch

var polyline=new qq.maps.Polyline({
map, // Which map to mark
path, // An array of coordinates from which polylines and polygons are formed
strokeColor, // Crease color
strokeDashStyle, // Polyline style
strokeWeight, // Crease width
editable, // Whether the polyline can be edited
clickable // Whether clickable
})
Copy the code

Single annotation point

The initialization map method is called during the Mounted lifecycle or after information is obtained 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 hover tag displays the 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 point group

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

initMap (arr) {
    // By default, the array is centered on the first item
    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>`);
            // Display window location
            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. Personalized map styles

Why to use personalized map, improve the map display effect and user experience in different scenarios.Why choose Tencent location service personalized map:

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

5. Tencent Location entry steps

1. Log in to Tencent location services

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

Location presentation componentRoute planning componentMap selection componentFront end positioning assembly

3. Wechat small program JavaScript SDK

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

onLoad() {
	console.log('Page loaded')
	// Instantiate the API core class
	qqmapsdk = new QQMapWX({
		// key: 'application key'
	});
},
onShow() {
	console.log('The page is displayed')
	// Call 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 return is as follows:New QQMapWX(Options :Object)

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

Location search:

// Location search
nearbySearchBtn() {
	qqmapsdk.search({
		keyword: 'kfc'.// Search keywords
		location: 39.980014 ', 116.313972 '.// Set the peripheral search center
		success: (res) = > {
			var mks = []
			for (var i = 0; i < res.data.length; i++) {
				mks.push({ // Get the returned result and put 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 class, js file 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: 'application key'
				key: 'Apply yourself, mine won't be released.'
			});
		},
		onShow() {
			console.log('The page is displayed') // Call interface dadaqianduan
			qqmapsdk.search({
				keyword: 'hotel'.success: (res) = > {
					console.log(res);
				},
				fail: (err) = > {
					console.log(err);
				},
				complete: (cres) = > {
					console.log(cres); }})},onReady() {
			console.log('First rendering of the page is complete')},methods: {
			getsuggest(e) {
				console.log(e.detail.value)
			    qqmapsdk.getSuggestion({
			      keyword: e.detail.value, // The keyword entered by the user can be set to a fixed value, e.g. keyword:'KFC'
			      //region:' Beijing ', // set the city name, limit the region range shown in the keyword, non-mandatory parameter
			      success: (res) = > {// Callback after a successful search
			        console.log(res);
			        var sug = [];
			        for (var i = 0; i < res.data.length; i++) {
			          sug.push({ // Get the returned result and put 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 keywords
					location: 39.980014 ', 116.313972 '.// Set the peripheral search center
					success: (res) = > {
						var mks = []
						for (var i = 0; i < res.data.length; i++) {
							mks.push({ // Get the returned result and put 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('The page is 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: 'application key'
				key: ' '
			});
		},
		onShow() {
			console.log('The page is displayed')},onReady() {
			console.log('First rendering of the page is complete')},methods: {
			formSubmit(e) {
				qqmapsdk.reverseGeocoder({
					location: e.detail.value.reverseGeo || ' '.// Get the coordinates of the position passed in to the form, leaving the default current position unfilled
					//get_poi: 1, // Whether to return the list of surrounding POI: 1. Return; 0 is not returned (default) and is not required
					success: (res) = > {
						console.log(res);
						var res = res.result;
						var mks = [];
						/** * if get_poi is 1, retrieve poI data from the current location and display it on the map. i < result.pois.length; Title: 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 left unfilled, retrieve the target location as needed
						mks.push({ // Get the returned result and put 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: { // Display the address name on markers, depending on the needs
								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('The page is hidden')
		},
	}
</script>
Copy the code

Geocoder – Provides a transformation from the address description to the coordinates of the position, as opposed to the process of resolving the reverseGeocoder(). The preview effect is shown as follows:

formSubmit(e) {
    // Call the address resolution interface
    qqmapsdk.geocoder({
      // Get the form's incoming address, e.dyail.value. Geocoder
      address: e.detail.value, Address: no. 74 Haidian West Street, Caihefang Road, Haidian District, Beijing
      success: (res) = > {// Callback after success
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        // Mark the resolvable address location on the map according to the resolvable address
         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 according to the requirements
              content: latitude + ', ' + longitude,
              color: '# 000'.display: 'ALWAYS'}}].this.poi= { // Set the name of the map center variable according to your data
            latitude: Number(latitude),
            longitude:  Number(longitude),
          }
      },
      fail: (error) = > {
        console.error(error);
      },
      complete: (res) = > {
        console.log(res); }})}Copy the code

The preview is as follows:

formSubmit(e){
	    // Call the distance calculation interface
		console.log(this.start,'dadaqianduan')
	    qqmapsdk.calculateDistance({
	        // Mode: 'driving',// Optional values: 'driving', 'walking', not default: 'walking', optional
	        // The current default address is not specified in the from parameter
	        // Get the latitude and longitude of the form submission and set the FROM and to parameters (example string format)
	        / / 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.dyail.value. dest, // Destination coordinates
	        success: (res) = > {// Callback after success
	          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 in the dis array,
	          }
	          this.distance=dis
	        },
	        fail: (error) = > {
	          console.error(error);
	        },
	        complete: (res) = > {
	          console.log(res); }}); }},Copy the code

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

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

Obtain the urban areas and counties, and the renderings are as follows:

onShow() {
	console.log('The page is displayed')
	// Call the get city list interface
	qqmapsdk.getCityList({
		success: (res) = > { // Callback after success
			console.log(res);
			console.log('Province data:', res.result[0])
			var city = res.result[0];
			GetCityList getCityList getCityList getCityList getCityList getCityList
			qqmapsdk.getDistrictByCityId({
				// Enter the corresponding province ID to obtain the city data, enter the city ID to obtain the district county data, and so on
				id: city[0].id, // getCityList returns the Id of the data, for example: Beijing is '110000'
				success: (res) = > { // Callback after success
					console.log(res);
					console.log(Data of districts and counties 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 for the micro channel small program to provide basic punctuation ability, line and circle drawing interface map components and location display, map selection point and other map API location service capability support, so that developers can freely implement their own micro channel small 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!