Take your front end pinch to death, every day to learn cool cool, dada front programmer, wechat search [programmer Doraemon] pay attention to this different programmer.
Thank you for every programmer who loves the front end, no matter how strange the front end skills are, welcome to pay attention to add me to the group
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 that I’ll go back to the development tutorial and try to make each feature as familiar as possible.)
1. What is Tencent location service?
Tencent location service is undoubtedly access to location services and other information content, the product highlights:
- 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
- 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
- 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
- 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
- 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”!
- 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
@markertap
– means triggered when the mark point is clicked,e.detail={markerId}
@labeltap
– Clicklabel
When triggered,e.detail = {markerId}
@callouttap
– means triggered when clicking the bubble corresponding to the mark point,e.detail = {markerId}
@controltap
– means triggered when the control is clicked,e.detail = {controlId}
@regionchange
– Trigger when the field of view changes@tap
– Trigger when clicking on the map;App-nuve
2.9 Support to return latitude and longitude@updated
– Triggers when the map render update is 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:
id
Is the mark pointid
That type ofNumber
, mandatory,marker
Clicking the event callback returns thisid
, suggested for eachmarker
On the setNumber
typeid
Guarantee updatemarker
Have better performance.latitude
Latitude, typeNumber
, mandatory, floating point, range- 90 ~ 90
longitude
Longitude, typeNumber
, mandatory, floating point, range- 180 ~ 180
title
, annotation name, typeString
, is not required, it shows when clicked,callout
Will be ignored if it existsiconPath
, display icon, typeString
, mandatory, the path of the picture in the project directoryrotate
, rotation Angle, typeNumber
, not required, clockwise rotation Angle, range0 ~ 360
, the default is 0alpha
, annotation transparency, typeNumber
, not mandatory, default 1, no transparency, scope0 ~ 1
width
, annotate icon width and typeNumber
, the default is the actual width of the imageheight
, mark the height and type of ICONSNumber
The default value is the actual height of the imagecallout
, the type of bubble window above the custom mark pointObject
, not required – newline character is recognizedlabel
Add a label, type, next to the mark pointObject
, not required – newline character is recognizedanchor
, latitude and longitude in the annotation icon anchor point, the default bottom midpoint, is not mandatory,{x, y}, x represents landscape (0-1), y represents vertical (0-1). {x:.5, y: 1} represents the midpoint of the base
Bubble Callout at marker (Object type)
Marker array attributes Callout objects use attributes:
content
, text,String
color
, text color,String
fontSize
, text size,Number
borderRadius
.callout
Rounded edges,Number
bgColor
, background color,String
padding
, text margin white,Number
display
.'BYCLICK': click to display; 'ALWAYS' : often show
.String
textAlign
, text alignment. Valid values:left, right, center
.String
Marker label (Object type)
content
, text,String
color
, text color,String
fontSize
, text size,Number
- X, the coordinates of label, the origin is zero
marker
The corresponding latitude and longitude,Number
- Y, the coordinates of label, the origin is zero
marker
The corresponding latitude and longitude,Number
- BorderWidth, borderWidth, Number
- BorderColor, borderColor, String
- BorderRadius, rounded edges, Number
- BgColor, background color, String
- Padding, margin of text, Number
- TextAlign, text alignment. Valid values:
left, right, center
The String
polyline
Polyline specifies a series of coordinate points from the first entry to the last
points
, latitude and longitude array, type isArray
Must be filled, such as:[{latitude: 0, longitude: 0}]
color
, the color of the line, type isString
It is not necessary to do STH.#0000AA
width
, the width of the line, of typeNumber
And don’t have to fill indottedLine
, whether dotted line, type isBoolean
, the default valuefalse
arrowLine
, arrow line of typeBoolean
, the default value isfalse
arrowIconPath
, replace the arrow icon whose type isString
Don’t fill inarrowLine
fortrue
The default line with an arrow takes effectborderColor
, border color of the line, type isString
And don’t have to fill inborderWidth
, the thickness of the line, and the type isNumber
And don’t have to fill in
polygon
Polygon Specifies a series of coordinate points that generate a closed polygon from the points coordinate data
points
, latitude and longitude array,array
Must be filled, such as:[{latitude: 0, longitude: 0}]
strokeWidth
, stroke width,Number
, nostrokeColor
Stroke color,String
, nofillColor
, fill the color,String
, nozIndex
, set polygonZ
Axis numerical,Number
, no
circles
Circles Displays circles on a map
latitude
, latitude,Number
, required, floating point number, range- 90 ~ 90
longitude
And longitude,Number
, required, floating point number, range- 180 ~ 180
color
, stroke color,String
It is not necessary to do STH.#0000AA
fillColor
, fill the color,String
It is not necessary to do STH.#0000AA
radius
, the radius,Number
Will fillstrokeWidth
, stroke width,Number
And don’t have to fill in
controls
Controls displays controls on a map that do not move with the map
id
And controlsid
.Number
This id is returned by the event callback when the control is clickedposition
, control position on the map,Object
, mandatory, control relative to the map positioniconPath
, display icon,String
, mandatory, the project directory under the picture path, support relative path writing method, to'/'
The beginning represents the relative project root directory; Temporary paths are also supportedclickable
, is it clickable,Boolean
, do not need to fill, default unclickable
position
left
How far to the left edge of the map,Number
, the default value is 0top
How far from the upper edge of the map,Number
, the default value is 0width
, control width,Number
, the default is the width of the pictureheight
, control height,Number
, the default is the height of the picture
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 developed by UNIApp. Basic usage 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 following is an example of the markers used:
markers: [{
id: 1.// Number
title: '1'.// String- Annotate the roll call
rotate: 180.// Number - Clockwise rotation Angle. The value ranges from 0 to 360. The default value is 0
alpha: 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.png'.// Display the icon
}, {
id: 2.title: '2'.// String
latitude: 39.90.longitude: 116.39.callout: {
color: '#007AFF'.// Text color
bgColor: '#563BFF'./ / the background color
display: "ALWAYS".// 'BYCLICK': click to display; 'ALWAYS' : often show
fontSize: 15.textAlign: 'left'.// Text alignment. Valid values: left, right, center
padding: 10.// Text margin white
borderRadius: 5.content: Tencent Map,},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
type
.String
, the default value iswgs84
returngps
Coordinates,gcj02
Returns the NGS coordinates available foruni.openLocation
The coordinates of the,app
Platform goldSDK
Only returns are supported.gcj02
altitude
.Boolean
Pass intrue
Will return the height information, because obtaining the height requires high accuracy, will slow down the interface return speedgeocode
.Boolean
, do not fill in, defaultfalse
, whether to resolve the address informationsuccess
.Function
, mandatory. The interface invokes the callback function successfully. For details about the returned function, see the description of returned parametersfail
.Function
, the interface failed to call the callback functioncomplete
.Function
, the callback function that ends the interface call (executed on success or failure).
Return parameters for SUCCESS:
latitude
Latitude, floating point number, range is- 90 ~ 90
Negative numbers indicate the southern latitudelongitude
, longitude, floating point number, range is- 180 ~ 180
A negative number represents the west longitudespeed
, speed, floating point, unitsm/s
accuracy
Accuracy of positionaltitude
, height, unitm
verticalAccuracy
, vertical accuracy, unitm
(Android
Unable to get, return0
)horizontalAccuracy
, horizontal accuracy, unitm
address
, address information (onlyApp
This parameter needs to be configuredgeocode
fortrue
)
Address Indicates the address information
country
.String
, countries such as “China”, do not returnundefined
province
.String
, if the province name is “Beijing”, returnundefined
city
.String
, the city name, such as “Beijing”, is not returnedundefined
district
.String
, district, county name such as “Chaoyang district”, no returnundefined
street
.String
, street information, such as “Jiuxianqiao Road”, no returnundefined
streetNum
.String
, obtain the street number information, such as “3”, no returnundefined
poiName
.String POI
Information, such as “Electronics city. International electronic headquarters “, if not returnedundefined
postalCode
.String
Zip code, such as"100016"
If no, returnundefined
cityCode
.String
, city code, such as"010"
If no, returnundefined
Uni. ChooseLocation (OBJECT) Opens the map and selects a location.
latitude
.String
Latitude of destinationlongitude
.String
Don’t fill in the target longitudekeyword
.String
, do not need to fill in, search keyword, only App platform supportsuccess
.Function
Will fillfail
.Function
And don’t have to fill incomplete
.Function
And don’t have to fill in
Success Returns the following parameters:
name
, location nameaddress
, detailed addresslatitude
Latitude, floating point number, range is- 90 ~ 90
Negative numbers indicate southern latitudes, usegcj02
National bureau coordinate system.longitude
, longitude, floating point number, range is- 180 ~ 180
, negative numbers indicate the west longitude, usedgcj02
National 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('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
MapContext -mapContext is bound to a
This object has a list of methods:
getCenterLocation
OBJECT
Gets the latitude and longitude at the center of the current mapgcj02
The coordinate system can be useduni.openLocatio
nmoveToLocation
OBJECT
Move the center of the map to the current anchor pointmap
The component’sshow-location
usetranslateMarker
OBJECT
translationmarker
Draw theincludePoints
OBJECT
Zoom view shows all latitude and longitudegetRegion
OBJECT
Gets the view range of the current mapgetScale
OBJECT
Gets the zoom level of the current map$getAppMap
Gets native map objectsplus.maps.Map
The OBJECT argument list for getCenterLocation
Res = {longitude: “longitude “, latitude:” latitude “}
MoveToLocation OBJECT parameter list – Optional
TranslateMarker OBJECT parameter list
markerId
Number
Required to specifymarker
destination
Object
Required to specifymarker
Move to the target pointautoRotate
Boolean
Do not specify whether the rotation is automatic during movementmarker
rotate
Number
Don’t have to fill inmarker
Angle of rotationduration
Number
No need to specify animation duration, default1000ms
, translation and rotation are calculated separatelyanimationEnd
Function
You don’t have to fill in the animation end callback functionfail
Function
You don’t have to fill in callback functions for failed interface calls
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
Home click can be registered, apply for a get key:lbs.qq.com? Lbs_invite =VJJIFLV
Key management: Create a new key and fill in the corresponding information
1. 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
Introduced in need before use in the index. The HTML < script charset = “utf-8” SRC = “https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY” > < / script > can use map.
<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
- Log in to Tencent location service
- Verify mobile phone and email
- Application for key development (
Key
) - Choose the product you need
Lbs.qq.com/webApi/comp…
Location display componentRoute planning component
Map selection componentFront-end positioning assembly
Iii. Wechat small program JavaScript SDK
- I applied for a developer key
key
- open
webserviceAPI
Services: Console ->key
Administration -> Settings (those that use this featurekey
) – > checkwebserviceAPI
– > save
(The small program SDK needs to use some services of webserviceAPI, so the KEY to use this function needs to have corresponding permissions.)
Daily command usage: 10,000 times/Key—- Number of concurrent commands: 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
A small program that –JavaScriptSDK
Core classes –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
Reference address: lbs.qq.com/miniProgram…
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!
Plug-in market:Ext.dcloud.net.cn/plugin?id=3…You can download more to try to play, the subsequent update plug-in content.
Application Tencent map developers used key, link: lbs.qq.com? Lbs_invite =VJJIFLV
Exclusive invitation code: VJJIFLV
I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time!
This article is constantly updated, you can search “Programmer Doraemon” on wechat for the first time to read, reply [information] I prepared the first line of large factory materials, this article www.dadaqianduan.cn/#/ has been included, welcome Star.
XXX | creator training camp The campaign is under way…