騰訊地圖JavaScript API的應用
目錄
前言
隨着社會的高速發展,手機地圖已經成爲了生活中不可或缺的一部分,他出現在各種app中,比如外賣app需要展示配送的路線和距離,導航的app需要路線規劃和顯示路線擁擠情況,社交app需要顯示自己所在的位置和附近用戶的位置。基本上只要你做的產品涉及到地圖板塊,你都需要引進相關地圖api。那麼對於開發者來說,怎麼使用地圖的api來完成我們的功能點就變的至關重要啦,這篇博客就講解下騰訊地圖JavaScript API的應用。
正文
註冊騰訊位置服務賬號
點擊上面的鏈接,填寫註冊信息,點擊註冊按鈕進行註冊即可
完成開發者驗證,即可進行註冊key
設置祕鑰
獲取祕鑰
騰訊地圖的開發文檔
針對不同的平臺,騰訊地圖的api還是很全的
騰訊地圖的JavaScript API
這裏具體看下JavaScript API ,這是一個官方給的demo,如何創建地圖,並設置地圖初始化的參數,我們在源代碼編輯器裏去隨意改變下參數,點擊運行就出現代碼運行的效果,很方便開發者理解這個功能的參數的作用和效果,而且貼心的還寫了備註。
騰訊地圖demo
一、使用場景,查詢出發地到目的地路線規劃,我們先看下路線規劃的api給的例子,就知道接下來寫代碼的思路了,我們需要先獲取用戶輸入的起點位置的座標,在獲取終點座標的位置,然後調用接口獲取路線規劃的結果,最後根據結果繪畫路線即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>折線應用: 路線規劃</title>
</head>
<script charset="utf-8"
src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
<style>
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#mapContainer {
width: 100%;
height: 100%;
}
</style>
<body onload="initMap()">
<div id="mapContainer"></div>
</body>
</html>
<script>
//注:本例僅爲說明流程,不保證嚴謹
var map;
function initMap(){
//初始化地圖
map = new TMap.Map('mapContainer', {
center: new TMap.LatLng(39.980619,116.321277),//地圖顯示中心點
zoom:14 //縮放級別
});
//WebServiceAPI請求URL(駕車路線規劃默認會參考實時路況進行計算)
var url="https://apis.map.qq.com/ws/direction/v1/driving/"; //請求路徑
url+="?from=39.984039,116.307630"; //起點座標
url+="&to=39.977263,116.337063"; //終點座標
url+="&output=jsonp&callback=cb" ; //指定JSONP回調函數名,本例爲cb
url+="&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"; //開發key,可在控制檯自助創建
//發起JSONP請求,獲取路線規劃結果
jsonp_request(url);
}
//瀏覽器調用WebServiceAPI需要通過Jsonp的方式,此處定義了發送JOSNP請求的函數
function jsonp_request(url){
var script=document.createElement('script');
script.src=url;
document.body.appendChild(script);
}
//定義請求回調函數,在此拿到計算得到的路線,並進行繪製
function cb(ret){
var coords = ret.result.routes[0].polyline, pl = [];
//座標解壓(返回的點串座標,通過前向差分進行壓縮)
var kr = 1000000;
for (var i = 2; i < coords.length; i++) {
coords[i] = Number(coords[i - 2]) + Number(coords[i]) / kr;
}
//將解壓後的座標放入點串數組pl中
for (var i = 0; i < coords.length; i += 2) {
pl.push(new TMap.LatLng(coords[i], coords[i+1]));
}
display_polyline(pl)//顯示路線
//標記起終點marker
var marker = new TMap.MultiMarker({
id: 'marker-layer',
map: map,
styles: {
"start": new TMap.MarkerStyle({
"width": 25,
"height": 35,
"anchor": { x: 16, y: 32 },
"src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png'
}),
"end": new TMap.MarkerStyle({
"width": 25,
"height": 35,
"anchor": { x: 16, y: 32 },
"src": 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png'
})
},
geometries: [{
"id": 'start',
"styleId": 'start',
"position": new TMap.LatLng(39.984039,116.307630307503)
}, {
"id": 'end',
"styleId": 'end',
"position": new TMap.LatLng(39.977263,116.337063)
}]
});
}
function display_polyline(pl){
//創建 MultiPolyline顯示折線
var polylineLayer = new TMap.MultiPolyline({
id: 'polyline-layer', //圖層唯一標識
map: map,//繪製到目標地圖
//折線樣式定義
styles: {
'style_blue': new TMap.PolylineStyle({
'color': '#3777FF', //線填充色
'width': 8, //折線寬度
'borderWidth': 5, //邊線寬度
'borderColor': '#FFF', //邊線顏色
'lineCap': 'round', //線端頭方式
})
},
//折線數據定義
geometries: [
{
'id': 'pl_1',//折線唯一標識,刪除時使用
'styleId': 'style_blue',//綁定樣式名
'paths': pl
}
]
});
}
</script>
二、具體的demo的代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>騰訊地圖</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#container {
/*地圖(容器)顯示大小*/
width: 100%;
height: 100%;
z-index: 1;
}
.searchWrap {
position: absolute;
top: 30px;
left: 30px;
z-index: 2;
}
#list-group,
#list-group2,
.searchEnd {
display: none;
}
#closeBtn {
position: absolute;
top: -10px;
right: -14px;
}
.dropdown-menu .list-group-item.active{
color: #fff;
background-color: #007bff;
border-color: #007bff;
}
</style>
<!--引入Javascript API GL,參數說明參見下文-->
<script src="https://map.qq.com/api/gljs?v=1.exp&key=HMQBZ-XC7KD-WZ64J-PFOQM-CFMT6-HUBOX"></script>
</head>
<!-- 頁面載入後,調用init函數 -->
<body>
<!-- 定義地圖顯示容器 -->
<div id="container"></div>
<div class="searchWrap">
<div class="searchStart">
<div class="input-group mb-3">
<input type="text" autocomplete="off" id="search" class="form-control strtSiteIpt" placeholder="請輸入地點"
aria-describedby="basic-addon1">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon1">搜索</span>
</div>
</div>
<ul class="list-group" id="list-group">
<li class="list-group-item"></li>
</ul>
</div>
<div class="searchEndWrap">
<div class="searchEnd">
<div class="input-group mb-3">
<input type="text" autocomplete="off" id="search2" class="form-control strtSiteIpt" placeholder="請輸入地點"
aria-describedby="basic-addon2">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2" style="position: relative;">搜索<button class="close" id="closeBtn"><span aria-hidden="true">×</span></button></span>
</div>
</div>
<ul class="list-group" id="list-group2">
<li class="list-group-item"></li>
</ul>
</div>
</div>
<div class="btn-group">
<button type="button" id="pathLineSearch" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
路線
</button>
<!-- <div class="dropdown-menu">
<span data-val="driving" class="pathLineBtn list-group-item active">駕車</span>
<span data-val="walking" class="pathLineBtn list-group-item ">步行</span>
<span data-val="bicycling" class="pathLineBtn list-group-item ">騎行</span>
<span data-val="transit" class="pathLineBtn list-group-item ">公交</span>
</div> -->
</div>
</div>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>
<script>
$(function () {
//定義地圖中心點座標
var center = new TMap.LatLng(39.984120, 116.307484)
//定義map變量,調用 TMap.Map() 構造函數創建地圖
var map = new TMap.Map(document.getElementById('container'), {
center: center,//設置地圖中心點座標
zoom: 4, //設置地圖縮放級別
// pitch: 43.5, //設置俯仰角
// rotation: 45 //設置地圖旋轉角度
});
let markerLayer = new TMap.MultiMarker({
id: 'marker-layer',
map: map
});
function addMarker(latLng, id) {
markerLayer.add({
id: id,
position: latLng
});
var lng = latLng.lng
var lat = latLng.lat
// map.newLatLngZoom(new TMap.LatLng(lng,lat), 14);
}
//移除marker事件
function removeMarker(id) {
if (id) {
markerLayer.remove(id)
}
}
function display_polyline(pl) {
//創建 MultiPolyline顯示折線
let polylineLayer = new TMap.MultiPolyline({
id: 'polyline-layer', //圖層唯一標識
map: map,//繪製到目標地圖
//折線樣式定義
styles: {
'style_blue': new TMap.PolylineStyle({
'color': '#3777FF', //線填充色
'width': 8, //折線寬度
'borderWidth': 5, //邊線寬度
'borderColor': '#FFF', //邊線顏色
'lineCap': 'round', //線端頭方式
})
},
//折線數據定義
geometries: [
{
'id': 'pl_1',//折線唯一標識,刪除時使用
'styleId': 'style_blue',//綁定樣式名
'paths': pl
}
]
});
}
// 添加路線
function addlineLayer(res) {
var coords = res.result.routes[0].polyline, pl = [];
//座標解壓(返回的點串座標,通過前向差分進行壓縮)
var kr = 1000000;
for (var i = 2; i < coords.length; i++) {
coords[i] = Number(coords[i - 2]) + Number(coords[i]) / kr;
}
//將解壓後的座標放入點串數組pl中
for (var i = 0; i < coords.length; i += 2) {
pl.push(new TMap.LatLng(coords[i], coords[i + 1]));
}
display_polyline(pl)//顯示路線
}
let searchStartArr = [] // 開始地點數據
let searchStartVal = null
let searchEndArr = [] // 結束地點數據
let searchEndVal = null
let pathLineWay = 'driving' // 路線默認方式
// 搜索開始點
$('body').on('input', '#search',
function (e) {
var search = $('#search').val()
clearTimeout(window.setTimeOutSearch1)
window.setTimeOutSearch1 = setTimeout(() => {
searchStartArr = []
if (search === "") {
$('#list-group').hide()
} else {
$('#list-group').show()
}
$('#list-group').html(`<li class="list-group-item" id="0">
<span class="lleft">正在努力查找中<span>
<span class="lright"><span>
</li>`)
$.ajax({
type: "get",
url: "https://apis.map.qq.com/ws/place/v1/suggestion",
data: {
'keyword': search,
'key': 'HMQBZ-XC7KD-WZ64J-PFOQM-CFMT6-HUBOX',
'output': 'jsonp'
},
//key換成自己的
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "TXmap",
headers: {
'Content-Type': 'application/json'
},
success: function (response) {
if (response.status !== 0) {
console.log('請求失敗')
return
}
searchStartArr = response.data
let html = ''
response.data.forEach(item => {
html += `
<li class="list-group-item" id="${item.id}">
<span class="lleft">${item.title}<span>
<span class="lright">${item.address}<span>
</li>
`
});
$('#list-group').html(html)
}
});
}, 200)
}
)
$('.searchStart').on('click', '.list-group-item', function (e) {
if (searchStartVal !== null) {
removeMarker([searchStartVal.id])
}
let target = null
if ($(e.target).attr('class') === "list-group-item") {
target = $(e.target)
} else {
target = $(e.target).parents('.list-group-item')
}
searchStartVal = searchStartArr.find(item => {
return item.id == target.attr('id')
})
$('#search').val(searchStartVal.title)
$('#list-group').hide()
addMarker(searchStartVal.location, searchStartVal.id)
})
$('#basic-addon1').click(function() {
addMarker(searchStartVal.location, searchStartVal.id)
})
// 搜索結束點
$('body').on('input', '#search2',
function (e) {
let search = $('#search2').val()
clearTimeout(window.setTimeOutSearch2)
window.setTimeOutSearch2 = setTimeout(() => {
searchEndArr = []
if (search === "") {
$('#list-group2').hide()
} else {
$('#list-group2').show()
}
$('#list-group2').html(`<li class="list-group-item" id="0">
<span class="lleft">正在努力查找中<span>
<span class="lright"><span>
</li>`)
$.ajax({
type: "get",
url: "https://apis.map.qq.com/ws/place/v1/suggestion",
data: {
'keyword': search,
'key': 'HMQBZ-XC7KD-WZ64J-PFOQM-CFMT6-HUBOX',
'output': 'jsonp'
},
//key換成自己的
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "TXmap",
headers: {
'Content-Type': 'application/json'
},
success: function (response) {
if (response.status !== 0) {
console.log('請求失敗')
return
}
searchEndArr = response.data
let html = ''
response.data.forEach(item => {
html += `
<li class="list-group-item" id="${item.id}">
<span class="lleft">${item.title}<span>
<span class="lright">${item.address}<span>
</li>
`
});
$('#list-group2').html(html)
}
});
}, 200)
}
)
$('.searchEndWrap').on('click', '.list-group-item', function (e) {
if (searchEndVal !== null) {
removeMarker([searchEndVal.id])
}
let target = null
if ($(e.target).attr('class') === "list-group-item") {
target = $(e.target)
} else {
target = $(e.target).parents('.list-group-item')
}
searchEndVal = searchEndArr.find(item => {
return item.id == target.attr('id')
})
$('#search2').val(searchEndVal.title)
$('#list-group2').hide()
addMarker(searchEndVal.location, searchEndVal.id)
})
$('#basic-addon2').click(function() {
addMarker(searchEndVal.location, searchEndVal.id)
})
// 路徑搜索
$('#pathLineSearch').click((e) => {
if($(".searchEnd").is(":hidden")) {
$('.searchEnd').show()
return
}
if (searchStartVal === null) {
alert('請輸入結束出發地')
return
}
if (searchEndVal === null) {
alert('請輸入結束目的地')
return
}
$.ajax({
type: "get",
url: "https://apis.map.qq.com/ws/direction/v1/" + pathLineWay + "/",
data: {
"from": searchStartVal.location.lat + ',' + searchStartVal.location.lng,
"from_poi": searchStartVal.id,
"to": searchEndVal.location.lat + ',' + searchEndVal.location.lng,
"to_poi": searchEndVal.id,
'key': 'HMQBZ-XC7KD-WZ64J-PFOQM-CFMT6-HUBOX',
'output': 'jsonp'
},
//key換成自己的
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "TXmap",
headers: {
'Content-Type': 'application/json'
},
success: function (response) {
addlineLayer(response)
}
});
})
$('.pathLineBtn').click(function() {
$('.pathLineBtn').removeClass('active')
$(this).addClass('active')
pathLineWay = $(this).attr('data-val')
})
$('#closeBtn').click(function() {
if (searchEndVal !== null) {
removeMarker([searchEndVal.id])
}
$('.searchEnd').hide()
searchEndArr = []
searchEndVal = null
})
});
</script>
</html>
總結
這裏我就拋轉引玉下,總體感覺騰訊位置服務上手還是很快的,api還是很完善的,示例的註解也相對完善,註冊簡便這塊我是真的喜歡,畢竟對於程序員來說,最喜歡簡單,簡單的界面,簡潔的代碼,都讓開發者心情無比舒暢。
感興趣的小夥伴,或者做自己項目用到地圖的小夥伴們趕緊註冊用用吧!有問題大家還能一起討論!
我是阿達,一名喜歡分享知識的程序員,時不時的也會荒腔走板的聊一聊電影、電視劇、音樂、漫畫,這裏已經有16496位小夥伴在等你們啦,感興趣的就趕緊來點擊關注我把,哪裏有不明白或有不同觀點的地方歡迎留言!