當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
高德地图JS API 使用01
生活随笔
收集整理的這篇文章主要介紹了
高德地图JS API 使用01
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
最近做項(xiàng)目,有個(gè)需求使用到高德地圖JS API,現(xiàn)寫(xiě)博客總結(jié)一下。
需求要求大概是這樣的:
- 使用地圖高德或百度或谷歌都可以(這里吐槽一下,百度地圖的jsAPI幫助文檔寫(xiě)的太。。。谷歌你懂的。。。高德目前感覺(jué)非常nice)
- 需要根據(jù)用戶定位獲取周邊片區(qū)相關(guān)數(shù)據(jù)統(tǒng)計(jì),并展示
- 頭部根據(jù)用戶點(diǎn)擊poi點(diǎn)信息而變更
- 點(diǎn)擊左上列表任意一列,地圖中心自動(dòng)切換并展示出信息框
- 效果圖如下:
緊接著帶著需求我就去高德地圖JSAPI尋找解決辦法,很驚喜發(fā)現(xiàn)有相關(guān)解決辦法,高德地圖JSAPI-UI組件事例中,標(biāo)注列表-完整事例?比較接近,只要稍微改造一下即可。
具體代碼如下:
map_house.js
/*** 使用高德地圖 1、先定位獲取用戶位置 2、定位成功后獲取區(qū)域統(tǒng)計(jì)數(shù)據(jù)*/ $("#panel").hide(); // 創(chuàng)建地圖 var map = new AMap.Map('container', {zoom: 15 }); var options = {'showButton' : true,// 是否顯示定位按鈕'buttonPosition' : 'LB',// 定位按鈕的位置/* LT LB RT RB */'buttonOffset' : new AMap.Pixel(10, 20),// 定位按鈕距離對(duì)應(yīng)角落的距離'showMarker' : true,// 是否顯示定位點(diǎn)'markerOptions' : {// 自定義定位點(diǎn)樣式,同Marker的Options'offset' : new AMap.Pixel(-18, -36),'content' : '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>'},'convert':true,//是否使用坐標(biāo)偏移,取值true:為高德地圖坐標(biāo),取值false:為瀏覽器定位坐標(biāo)默認(rèn)值:true'timeout':1000,// 定位超時(shí)'GeoLocationFirst':true,//默認(rèn)為false,設(shè)置為true的時(shí)候可以調(diào)整PC端為優(yōu)先使用瀏覽器定位,失敗后使用IP定位'zoomToAccuracy':true,// 定位成功后調(diào)整地圖視野范圍使定位位置及精度范圍視野內(nèi)可見(jiàn),默認(rèn):false'showCircle' : true,// 是否顯示定位精度圈'circleOptions' : {// 定位精度圈的樣式'strokeColor' : '#0093FF','noSelect' : true,'strokeOpacity' : 0.5,'strokeWeight' : 1,'fillColor' : '#02B0FF','fillOpacity' : 0.25}}AMap.plugin([ "AMap.Geolocation" ], function() {// 定位 -開(kāi)始var geolocation = new AMap.Geolocation(options);map.addControl(geolocation);geolocation.getCurrentPosition();// 返回定位信息AMap.event.addListener(geolocation, 'complete', onComplete);// 返回定位錯(cuò)誤信息AMap.event.addListener(geolocation, 'error', onError); });// 定位成功function onComplete(data) {}// 定位失敗function onError(data) {var str = '';str += '錯(cuò)誤信息:'switch (data.info) {case 'PERMISSION_DENIED':str += '瀏覽器阻止了定位操作';break;case 'POSITION_UNAVAILBLE':str += '無(wú)法獲得當(dāng)前位置';break;case 'TIMEOUT':str += '定位超時(shí)';break;default:str += '未知錯(cuò)誤';break;}alert(str);}// 加載數(shù)據(jù)oninstall(); function oninstall(){AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],function(MarkerList, SimpleMarker, SimpleInfoWindow) {// 即jQuery/Zeptovar $ = MarkerList.utils.$;var defaultIconStyle = 'red', // 默認(rèn)的圖標(biāo)樣式hoverIconStyle = 'green', // 鼠標(biāo)hover時(shí)的樣式selectedIconStyle = 'purple' // 選中時(shí)的圖標(biāo)樣式;var markerList = new MarkerList({map: map,// ListElement對(duì)應(yīng)的父節(jié)點(diǎn)或者IDlistContainer: "myList", // document.getElementById("myList"),// 選中后顯示// 從數(shù)據(jù)中讀取位置, 返回lngLatgetPosition: function(item) {return [item.arealongitude, item.arealatitude];},// 數(shù)據(jù)ID,如果不提供,默認(rèn)使用數(shù)組索引,即indexgetDataId: function(item, index) {return item.id;},getInfoWindow: function(data, context, recycledInfoWindow) {// 排除統(tǒng)計(jì)為0的數(shù)據(jù)if(data.totalNum!=0){ if (recycledInfoWindow) {recycledInfoWindow.setInfoTitle(data.areaName);recycledInfoWindow.setInfoBody("剩余:"+data.totalNum+" 套");return recycledInfoWindow;}return new SimpleInfoWindow({infoTitle: data.areaName,infoBody: "剩余:"+data.totalNum+" 套",offset: new AMap.Pixel(0, -37)});}return;},// 構(gòu)造marker用的options對(duì)象,// content和title支持模板,也可以是函數(shù),返回marker實(shí)例,或者返回options對(duì)象getMarker: function(data, context, recycledMarker) {// 排除統(tǒng)計(jì)為0的數(shù)據(jù)if(data.totalNum!=0){ if($("#panel").is(':hidden')){$("#panel").show();}var label = String.fromCharCode('A'.charCodeAt(0) + context.index);if (recycledMarker) {recycledMarker.setIconLabel(label);return;}return new SimpleMarker({containerClassNames: 'my-marker',iconStyle: defaultIconStyle,iconLabel: label});}return;},// 構(gòu)造列表元素,與getMarker類(lèi)似,可以是函數(shù),返回一個(gè)dom元素,或者模板 html stringgetListElement: function(data, context, recycledListElement) {if(data.totalNum!=0){ var label = String.fromCharCode('A'.charCodeAt(0) + context.index);// 使用模板創(chuàng)建var innerHTML = MarkerList.utils.template('<div class="poi-info-left">' +' <h3 class="poi-title">' +label +'.'+data.areaName +' </h3>' +' <div class="poi-info">' +' <p class="poi-addr">剩余:'+data.totalNum+' 套</p>' +' </div>' +'</div>' +'<div class="clear"></div>', {data: data,label: label});if (recycledListElement) {recycledListElement.innerHTML = innerHTML;return recycledListElement;}return '<li class="poibox">' +innerHTML +'</li>';}},// 列表節(jié)點(diǎn)上監(jiān)聽(tīng)的事件listElementEvents: ['click', 'mouseenter', 'mouseleave'],// marker上監(jiān)聽(tīng)的事件markerEvents: ['click', 'mouseover', 'mouseout'],// makeSelectedEvents:false,selectedClassNames: 'selected',autoSetFitView: true});window.markerList = markerList;markerList.on('selectedChanged', function(event, info) {// checkBtnStats();if (info.selected) {// 切換頁(yè)面標(biāo)題$("#titleId").html("廣西-南寧市-"+info.selected.data.areaName+" 房源數(shù):"+info.selected.data.totalNum+" 套");console.log(info);if (info.selected.marker) {// 更新為選中樣式info.selected.marker.setIconStyle(selectedIconStyle);}// 選中并非由列表節(jié)點(diǎn)上的事件觸發(fā),將關(guān)聯(lián)的列表節(jié)點(diǎn)移動(dòng)到視野內(nèi)if (!info.sourceEventInfo.isListElementEvent) {if (info.selected.listElement) {scrollListElementIntoView($(info.selected.listElement));}}}if (info.unSelected && info.unSelected.marker) {// 更新為默認(rèn)樣式info.unSelected.marker.setIconStyle(defaultIconStyle);}});markerList.on('listElementMouseenter markerMouseover', function(event, record) {if (record && record.marker) {forcusMarker(record.marker);// this.openInfoWindowOnRecord(record);// 非選中的idif (!this.isSelectedDataId(record.id)) {// 設(shè)置為hover樣式record.marker.setIconStyle(hoverIconStyle);// this.closeInfoWindow();}}});markerList.on('listElementMouseleave markerMouseout', function(event, record) {if (record && record.marker) {if (!this.isSelectedDataId(record.id)) {// 恢復(fù)默認(rèn)樣式record.marker.setIconStyle(defaultIconStyle);}}});// 數(shù)據(jù)輸出完成markerList.on('renderComplete', function(event, records) {// checkBtnStats();console.log(event);console.log(records);var typeStatus=0;$.each(records, function(i,val){ if(val.data.totalNum!=0){// 更新頁(yè)面頭部提示$("#titleId").html("請(qǐng)點(diǎn)擊標(biāo)注或左上列表選項(xiàng),進(jìn)行房源數(shù)量查看");typeStatus=1;}});if(typeStatus==0){$("#titleId").html("暫無(wú)相關(guān)數(shù)據(jù)");}});// 加載數(shù)據(jù)function loadData(src, callback) {$.getJSON(src, function(data) {if(data.data==null){$("#titleId").html("暫無(wú)相關(guān)數(shù)據(jù)");$("#panel").hide();return;}console.log(data.data);markerList._dataSrc = src;// 渲染數(shù)據(jù)markerList.render(data.data);if (callback) {callback(null, data.data);}});}var $btns = $('#btmlod');/*** 檢測(cè)各個(gè)button的狀態(tài)*/ // function checkBtnStats() { // $('#btnList input[data-enable]').each(function() {// // var $input = $(this), // codeEval = $input.attr('data-enable');// // $input.prop({ // disabled: !eval(codeEval) // }); // }); // }// 初始化loadData($btns.attr('data-path'));function forcusMarker(marker) {marker.setTop(true);// 不在地圖視野內(nèi)if (!(map.getBounds().contains(marker.getPosition()))) {// 移動(dòng)到中心map.setCenter(marker.getPosition());}}function isElementInViewport(el) {var rect = el.getBoundingClientRect();return (rect.top >= 0 &&rect.left >= 0 &&rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /** or* $(window).height()*/rect.right <= (window.innerWidth || document.documentElement.clientWidth) /** or* $(window).width()*/);}function scrollListElementIntoView($listEle) {if (!isElementInViewport($listEle.get(0))) {$('#panel').scrollTop($listEle.offset().top - $listEle.parent().offset().top);}// 閃動(dòng)一下$listEle.one('webkitAnimationEnd oanimationend msAnimationEnd animationend',function(e) {$(this).removeClass('flash animated');}).addClass('flash animated');}});}html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ include file="/WEB-INF/views/include/mobile/taglib.jsp"%> <title>${fns:getConfig('productName')}</title> <link rel="stylesheet" type="text/css" href="${ctxStatic}/rent/css/map_css.css"> </head> <body><div id="outer-box"><div class="popup" id="titleId">正在加載...</div><div id="container" tabindex="0"></div><!-- 列表 --><div id="panel" class="scrollbar1"><ul id="myList"></ul></div></div><!-- 數(shù)據(jù)地址,ajax,需返回json --><input type="hidden" id="btmlod" data-path="${conPathRennt}/mobile/rentHouse/mapJson"> </body> <script type="text/javascript"src="${ctxStatic}/rent/js/jquery-1.8.3.min.js"></script> <script type="text/javascript"src="https://webapi.amap.com/maps?v=1.4.7&key=你的key"></script><!-- UI組件庫(kù) 1.0 --> <script src="https://webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script> <script src="${ctxStaticRent }/js/map_house.js" type="text/javascript"></script> </html>css
html, body{ width:100%; height:100%; margin:0px; padding:0; font-size:13px; } ul, li{ padding:0; margin:0; list-style:none; } #outer-box{ /* height:100%; */ /* padding-right:100px; */ } #container{ height:100%; width:100%; } #panel{ position:absolute; top:60; /* bottom:0; */ left:0; height:300px; overflow:auto; width:100px; z-index:999; border-left:1px solid #eaeaea; background:#fff; } #btnList{ position:absolute; right:300px; top:0; padding:0; margin:0; z-index:999; } #btnList li{ padding:5px; } #btnList input{ padding:3px 10px; min-width:120px; } li.poibox{ border-bottom:1px solid #eaeaea; border-left:2px solid rgba(0,0,0,0); padding:10px 3px; cursor:pointer; } li.poibox.selected{ border-left-color:#f00; background:#f6f6f6; } li.poibox:hover{ background:#f6f6f6; } li.poibox:last-child{ border-bottom:none; } h3.poi-title{ margin:3px 0; font-size:13px; } .poibox .poi-info-left{ padding-left:8px } .poi-addr{ margin:7px 0 0; } .poibox .poi-imgbox{ width:100px; height:74px; vertical-align:top; float:right; margin:0 8px; overflow:hidden } .poibox .poi-img{ display:inline-block; width:100%; height:100%; background-size:cover; background-position:50% 50%; } .amap-simple-marker.my-marker .amap-simple-marker-label{ font-size:12px; color:#eee; font-family:sans-serif; } .selected .amap-simple-marker.my-marker .amap-simple-marker-label{ font-size:14px; color:orange; font-weight:700; } @-webkit-keyframes flash{ from, 50%, to{ opacity:1; } 25%, 75%{ opacity:0; } } @keyframes flash{ from, 50%, to{ opacity:1; } 25%, 75%{ opacity:0; } } .flash{ -webkit-animation-name:flash; animation-name:flash; } .animated{ -webkit-animation-duration:1s; animation-duration:1s; -webkit-animation-fill-mode:both; animation-fill-mode:both; } .scrollbar1::-webkit-scrollbar-track{ -webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3); background-color:#fff; } .scrollbar1::-webkit-scrollbar{ width:6px; background-color:#fff; } .scrollbar1::-webkit-scrollbar-thumb{ background-color:#aaa; } .clear{ clear:both; }/* body, html {width: 100%;height: 100%;margin: 0;font-family: "微軟雅黑"; }#container {width: 100%;height: 600px; } */p {margin-left: 15px;font-size: 14px; /* padding: 20px 0px 0px 0px; */ }.popup {z-index: 99999;position: absolute;text-align: center;border: none;text-align: center;width: 100%;height: 60px;font: 16px/60px Tahoma, Verdana, sans-serif;box-shadow: 0 10px 14px rgba(0, 0, 0, 0.4);color: #fefefe;background: #1e90ff; }.content-window-card {z-index: 99999;position: relative;box-shadow: none;bottom: 0;left: 0;width: auto;padding: 0; }.content-window-card p {height: 2rem; }.custom-info {border: solid 1px silver; }div.info-top {position: relative;background: none repeat scroll 0 0 #F9F9F9;border-bottom: 1px solid #CCC;border-radius: 5px 5px 0 0; }div.info-top div {display: inline-block;color: #333333;font-size: 14px;font-weight: bold;line-height: 31px;padding: 0 10px; }div.info-top img {position: absolute;top: 10px;right: 10px;transition-duration: 0.25s; }div.info-top img:hover {box-shadow: 0px 0px 5px #000; }div.info-middle {font-size: 12px;padding: 10px 6px;line-height: 20px; }div.info-bottom {height: 0px;width: 100%;clear: both;text-align: center; }div.info-bottom img {position: relative;z-index: 104; }span {margin-left: 5px;font-size: 11px; }.info-middle img {float: left;margin-right: 6px; }參考鏈接:
事例:https://lbs.amap.com/api/amap-ui/demos/amap-ui-markerlist/index
API:https://lbs.amap.com/api/javascript-api/summary
總結(jié)
以上是生活随笔為你收集整理的高德地图JS API 使用01的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SETP7 Professional V
- 下一篇: summernote编辑器插件使用笔记