🍊jquery
实现点击菜单实现高德地图定位点与数据展示联动效果
版本介绍:
- jQuery v3.7.1
- 高德地图JS API 2.0
代码仓库 ⭐
Gitee
:实现点击菜单实现高德地图定位点与数据展示联动效果
1.启动说明 📔
- 推荐
VS Code
编辑器 - 插件
Live Server
插件 - 使用
Live Server
启动index.html
,访问即可
2. 效果图加功能说明 🔨
-
效果图1:(点击省份进入城市
marker
点标记)
-
效果图2:(点击左侧菜单定位对应
marker
点) -
效果图3:(初始页面,点击左侧市场菜单,进入菜单列表页并将
marker
标记添加)
-
效果图4:(
marker
标记信息弹窗内点击,返回到省份)
4. 文件结构 📚
├─ data
│ ├─ getLeftMenu.json # 左侧菜单数据
│ ├─ getProvinceClass.json # 获取省code数据
│ ├─ getProvinceClass.json # 省份信息弹窗数据
├─ css
│ ├─ amap.css # 地图与左侧菜单样式
│ ├─ base.css # 基础样式文件
├─ js
│ ├─ amap.js # 地图与左侧菜单js文件
│ ├─ jquery-3.7.1.json # 基础样式文件
├─ index.html # 入口文件
5. 示例代码 📖
index.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><link rel="stylesheet" href="./css/base.css"><link rel="stylesheet" href="./css/amap.css"><link rel="stylesheet" href="https://style.feijiu.net/css/shichang/scbase.css"><link rel="stylesheet" href="https://style.feijiu.net/css/shichang/scindex.css"><script src="./js/jquery-3.7.1.js"></script><script src="https://webapi.amap.com/loader.js"></script><script src="./js/amap.js"></script>
</head><body><div class="container"><!-- 左侧菜单 --><div class="menuContainer" id="menuContainer"><a href="javascript:void(0);" onclick="getMenu('水果市场')" title="水果市场">水果市场</a></div><!-- 地图区域 --><div class="mapContainer" id="mapContainer"></div></div><script type="text/javascript">window._AMapSecurityConfig = {securityJsCode: "「你申请的安全密钥」", };</script><script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=替换为你申请的 key"></script><!-- 加载高德地图 --><script type="text/javascript">initialize()$(document).ready(function () {$ajax('getProvinceClass', drawMapText)});</script><!-- 封装ajax方法 --><script type="text/javascript">const $ajax = (url, cb) => {$.ajax({url: `./data/${url}.json`,type: 'GET',dataType: 'json',success: function (data) {cb && cb(data)},error: function (xhr, status, error) {console.error("Error loading JSON file: " + error);}});}</script>
</body></html>
- 逻辑文件
amap.js
/*** @function getPosition* @description 初始化处理省数据,用于定位Marker和targetName显示* @param {string} adcode: 区域编码*/
const getPosition = (adcode) => {let str = "";switch (adcode) {case "110000":str = "北京市_116.395825_39.941005";break;case "120000":str = "天津市_117.210813_39.14393";break;case "130000":str = "河北省_115.177813_38.206007";break;case "140000":str = "山西省_112.564662_37.872049";break;case "150000":str = "内蒙古_110.052771_41.34515";break;case "210000":str = "辽宁省_123.004468_41.455972";break;case "220000":str = "吉林省_126.346847_43.833111";break;case "230000":str = "黑龙江省_128.664906_46.690662";break;case "310000":str = "上海市_121.416372_31.45115";break;case "320000":str = "江苏省_119.31908_32.642047";break;case "330000":str = "浙江省_120.827658_30.180849";break;case "340000":str = "安徽省_116.840281_31.83996";break;case "350000":str = "福建省_118.680011_26.017147";break;case "360000":str = "江西省_116.545924_28.190379";break;case "370000":str = "山东省_118.900778_36.486773";break;case "410000":str = "河南省_114.779784_34.986831";break;case "420000":str = "湖北省_113.602357_30.892777";break;case "430000":str = "湖南省_112.130573_27.929244";break;case "440000":str = "广东省_114.083052_23.555889";break;case "450000":str = "广西_109.152576_23.080123";break;case "460000":str = "海南省_110.072441_19.494242";break;case "500000":str = "重庆市_107.377359_29.631998";break;case "510000":str = "四川省_103.182775_30.528033";break;case "520000":str = "贵州省_106.199932_26.399788";break;case "530000":str = "云南省_102.189321_24.66383";break;case "540000":str = "西藏_92.365164_29.792605";break;case "610000":str = "陕西省_108.334018_34.150637";break;case "620000":str = "甘肃省_104.249818_35.756198";break;case "630000":str = "青海省_100.975099_36.353776";break;case "640000":str = "宁夏_107.119797_38.322051";break;case "650000":str = "新疆_88.538527_43.616418";break;case "710000":str = "台湾_121.359304_24.461909";break;case "810000":str = "香港_115.067429_22.630108";break;case "820000":str = "澳门_113.338083_22.151047";break;default:str = "北京市_116.395825_39.941005";break;}const position = str.split("_");return {targetName: position[0],longitude: position[1],latitude: position[2],};
};/*** @function initialize* @description 初始化渲染地图*/
let map = undefined;
const initialize = () => {map = new AMap.Map("mapContainer", {zoom: 4,zooms: [4, 20],center: [116.404, 39.915],});map.plugin(["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", "AMap.HawkEye"],() => {map.addControl(new AMap.Scale()); //比例尺map.addControl(new AMap.ToolBar({position: "RT",})); //工具条map.addControl(new AMap.ControlBar()); //工具条方向盘map.addControl(new AMap.HawkEye()); //鹰眼});
};/*** @function drawMapText* @description 主要用于自定义文本点标记Marker* @param {string} adlist:区域列表*/
const drawMapText = (adlist) => {const { list = [] } = adlist;list.forEach((item) => {const position = getPosition(item.province_code);const { targetName, longitude, latitude } = position;const mapText = new AMap.Text({text: targetName,position: [longitude, latitude],topWhenClick: "true",anchor: "center",cursor: "pointer",style: {width: "52px",height: "18px",padding: "0",textAlign: "center",lineHeight: "18px",fontSize: "12px",fontWeight: "700",color: "#fff",border: "none",borderRadius: "5px",backgroundColor: "#f5222d",whiteSpace: "nowrap",MozUserSelect: "none",},});mapText.on("mouseover", () => {mapText.setStyle({backgroundColor: "#096dd9",});});mapText.on("mouseout", () => {mapText.setStyle({backgroundColor: "#f5222d",});});mapText.on("click", () => {drawProvinceInfo(item.province_code, position);});mapText.add(map);});
};/*** @function drawProvinceInfo* @description 点击自定义Marker省份按钮,渲染信息窗体* @param {string} adcode:区域编码* @param {string} targetName:当前省名称* @param {string} longitude:当前经度* @param {string} latitude:当前维度*/
const drawProvinceInfo = (adcode, { targetName, longitude, latitude }) => {$ajax("getProvinceInfo", ({ data: { domContent = "", count = 0 } }) => {const content = `<div class="infoContainer"><div class="infoTitle"><h2>${targetName}</h2><span>${targetName}范围内共<b style="color:#f5222d;">${count}</b>种水果</span></div><div class="infoContent"><div class="infoContentTitle">水果种类</div><ul class="infoContentBox">${domContent}</ul></div><div class="infoBottom"><button οnclick="drawProvinceDistribute('${adcode}')">${targetName}市场分布</button></div></div>`;const infoWindow = new AMap.InfoWindow({isCustom: false,closeWhenClickMap: true,content,offset: new AMap.Pixel(0, -10),});infoWindow.open(map, [longitude, latitude]);});
};/*** @function drawProvinceDistribute* @description 点击市场分布按钮,查看全部市场分部与渲染区域边界* @param {string} adcode:区域编码*/
const drawProvinceDistribute = (adcode) => {const { targetName, longitude, latitude } = getPosition(adcode);// 清除地图图层等操作map.setZoomAndCenter(6, [longitude, latitude], true);map.setZooms([5, 20]);// 绘制边界drawBounds(adcode);// 获取市场数据getMenu(targetName);
};/*** @function drawBounds* @description 绘制行政省边界区域* @param {string} keyword:行政区code*/
let district = null;
let polygon = null;
const drawBounds = (keyword) => {map.plugin("AMap.DistrictSearch", () => {if (!district) {//实例化DistrictSearchdistrict = new AMap.DistrictSearch({subdistrict: 0,extensions: "all",level: "province",});}// 行政区查询district.search(keyword, (status, result) => {if (polygon) {map.remove(polygon); //清除上次结果polygon = null;}if (status !== "complete") {return;}const bounds = result.districtList[0].boundaries;if (bounds) {//生成行政区划polygonfor (let i = 0; i < bounds.length; i += 1) {//构造MultiPolygon的pathbounds[i] = [bounds[i]];}polygon = new AMap.Polygon({strokeWeight: 1,path: bounds,fillOpacity: 0.4,fillColor: "#80d8ff",strokeColor: "#0091ea",});map.add(polygon);// 视口自适应map.setFitView(polygon, true, [60, 60, 60, 60]);}});});
};/*** @Start 市场分布* --------------------------------------------------------------------*//*** @function getMenu* @description 获取市场列表数据并渲染在左侧菜单区域* @param {string} urlFlag: 区分url标记* @param {string} title:行业标题* @param {string} adcode:区域编码*/
const getMenu = (title) => {map.clearMap();// 请求菜单数据$ajax("getLeftMenu", ({ list: menus = [] }) => {let menuHTML = `<div class="menuTitle"><a href="javascript:void(0)" οnclick="location.reload()">所有市场</a>><span>所选:</span><span class="menuSelected"> ${title}</span></div><div>`;menus.forEach((menu, idx) => {menuHTML += `<div class="menuBox" sort="${idx + 1}"><div class="icon">${idx + 1}</div><div class="menuContent"><div class="menuName">${menu.name}</div><div class="menuInfo"><p>经营范围:${menu.businessScope}</p><p>供求信息:${menu.supplyNum}条</p><p>现货信息:${menu.stockNum}条</p></div></div></div>`;// 地图添加市场标记drawMapMarker(menu, idx + 1 + "");});document.getElementById("menuContainer").innerHTML = menuHTML + "</div>";// 绑定事件bindMenuEvent(menus);});
};/*** @function bindMenuEvent* @description 左侧菜单元素绑定移入移出和点击事件*/
const bindMenuEvent = (menus) => {jQuery("div.menuBox").hover(function () {$(this).children("div.icon").css("background-color", "#fff");$(this).children("div.icon").css("color", "#2e3243");const sort = $(this).attr("sort");mapMarkHighlight(sort, true);},function () {$(this).children("div.icon").css("background-color", "#333333");$(this).children("div.icon").css("color", "#fff");const sort = $(this).attr("sort");mapMarkHighlight(sort);});jQuery("div.menuBox").click(function () {$(this).children("div.icon").css("background-color", "#fff");$(this).children("div.icon").css("color", "#2e3243");const sort = $(this).attr("sort");drawMarketInfo(menus[sort - 1]);});
};/*** @function drawMapMarker* @description 为地图上添加市场对应的Marker标记* @param {object} menu:市场数据* @param {string} idx:索引*/
const drawMapMarker = (menu, idx) => {const longitude = menu.longitude * 1;const latitude = menu.latitude * 1;const mapMarker = new AMap.Marker({map: map,size: new AMap.Size(25, 33),content: `<div class="marketIcon">${idx}</div>`,position: [longitude, latitude],offset: new AMap.Pixel(-13, -30),});mapMarker.on("mouseover", () => {mapMarkHighlight(idx, true);});mapMarker.on("mouseout", () => {mapMarkHighlight(idx);});mapMarker.on("click", () => {drawMarketInfo(menu);});
};/*** @function mapMarkHighlight* @description 地图标志高亮* @param {string} idx: 当前移入的marker索引* @param {boolean} isHover:是否移入*/
const mapMarkHighlight = (idx, isHover = false) => {jQuery.each(jQuery("div.marketIcon"), function () {if (jQuery(this).html() === idx && isHover) {jQuery(this).addClass("marketIcon-hover");} else {jQuery(this).removeClass("marketIcon-hover");}});
};/*** @function drawMarketInfo* @description 点击市场信息自定义Marker点,渲染市场详情信息窗体* @param {string} info:当前市场详情信息*/
let marketInfo = null;
const drawMarketInfo = (info) => {if (marketInfo !== null) {marketInfo.close();marketInfo = null;}const content = `<div class="marketContainer"><a href='${info.link}' target='_blank'><img src='${info.photo ||"https://img1.baidu.com/it/u=2063777893,3765279289&fm=253&fmt=auto&app=120&f=GIF?w=218&h=218"}'></a><div class='marketContent'><ul><li><b style='font-size:14px;'><a href='${info.link}' target='_blank'>${info.name}</a></b></li><li>经营范围:${info.businessScope}</li><li>供求信息:${info.supplyNum}</li><li>现货信息:${info.stockNum}</li></ul><div class= 'marketBottom'><a href="javascript:void(0);" οnclick="drawProvinceDistribute('${info.province}')">${getPosition(info.province)["targetName"]}所有市场</a></div></div></div>`;marketInfo = new AMap.InfoWindow({isCustom: false,closeWhenClickMap: true,content,offset: new AMap.Pixel(-5, -32),});const longitude = info.longitude * 1;const latitude = info.latitude * 1;map.setCenter([longitude, latitude], true);marketInfo.open(map, [longitude, latitude]);
};
amap.css
/* 点击省按钮信息窗体样式 */
.amap-info-content {padding: 0;
}/* close 按钮 */
.amap-info-close {top: 2px;right: 2px;background: #fff;
}.infoContainer {width: 320px;display: flex;flex-direction: column;
}.infoTitle {display: flex;justify-content: space-between;align-items: center;padding: 8px;
}.infoTitle span {margin-right: 10px;
}.infoContent {padding: 5px 0 0 8px;color: #666;border-top: 2px solid #d9d9d9;background-color: #e8e6e6;
}.infoContentTitle {font-size: 12px;font-weight: bold;border-bottom: 1px dotted #ccc
}ul.infoContentBox {height: 60px;padding-top: 6px;
}.infoBottom {padding: 8px 0;background: #fff;text-align: center;
}.infoBottom button {height: 30px;padding: 2px 5px;background: linear-gradient(45deg, #f5222d, #096dd9);color: #fff;border: none;border-radius: 4px;cursor: pointer;
}.infoBottom button:hover {filter: brightness(120%);filter: drop-shadow(0 0 2px rgba(0, 0, 0, .5))
}/* 市场信息窗体样式 */
.marketContainer {display: flex;width: 350px;height: 110px;overflow: hidden;border: 1px solid #999;background: #f6f6f6;
}.marketContainer a img {width: 130px;height: 100px;margin: 5px;object-fit: cover;
}.marketContent {display: flex;flex-direction: column;justify-content: space-between;overflow: hidden;margin: 5px;
}.marketContent ul {overflow: auto;
}.marketBottom {width: 200px;height: 20px;margin-top: 5px;border-top: 1px solid #ccc;
}.marketIcon {position: absolute;width: 20px;height: 32px;line-height: 16px;text-align: center;font-size: 12px;font-weight: 700;color: #fff;background: url('../images/icon_position.png') no-repeat 0 0px;cursor: pointer;white-space: nowrap;
}/* 修改Marker移入样式 */
.marketIcon-hover {background-position: 0 -33px !important;
}/* 左侧菜单样式 */.menuTitle {width: 100%;height: 50px;color: #fff;overflow: hidden;line-height: 50px;text-indent: 15px;font-size: 14px;background-color: #2e3243;border-bottom: 1px solid #f5222d;
}.menuTitle a {color: #fff;
}.menuSelected {color: #faad14;font-weight: 700;
}.menuBox {display: flex;justify-content: space-between;padding: 10px;border-bottom: 1px dotted #2e3243;cursor: pointer;
}.menuBox:hover{color: #fff;background-color: #2e3243;
}.menuBox .icon {width: 20px;height: 20px;text-align: center;line-height: 18px;color: #fff;background-color: #333333;border-radius: 20px;
}.menuBox .menuContent {display: flex;flex: 1;flex-direction: column;margin-left: 8px;line-height: 16px
}.menuBox .menuContent .menuName {font-weight: 700
}.menuBox .menuContent .menuInfo p{margin: 5px 0;
}
6. 数据文件: 文件内为虚拟数据,仅为展示效果
getLeftMenu.json
左侧菜单数据
{"list": [{"id": 1,"name": "苏州**交易市场","businessScope": "各种新鲜水果,如苹果、香蕉、橙子、梨、桃、葡萄等销售","photo": "https://inews.gtimg.com/om_bt/OP0mBSVgib26rrdC7oEbQWPeeAcQzNydGaqw6REufiCXcAA/641","province": "320000","city": "320500","stockNum": 7,"supplyNum": 28,"link": "#","longitude": "120.448306","latitude": "31.433461"},{"id": 2,"name": "上海**水果交易中心","businessScope": " ","photo": "https://inews.gtimg.com/om_bt/O5zWPSXGHr-o-U1vUxCw8AJ7onRB6wNsX9Qi82hPbTGDoAA/1000","province": "310000","city": "310100","stockNum": 3,"supplyNum": 0,"link": "#","longitude": "121.311438","latitude": "31.032425"},{"id": 3,"name": "河北**水果商圈","businessScope": "水果销售、水果礼盒、水果批发、水果配送、水果加工、水果咨询服务、代客挑选水果等","photo": "https://imgservice.suning.cn/uimg1/b2c/image/Wgur-Xf1xyKN3mwAnWLC0Q.jpg_800w_800h_4e","province": "130000","city": "130300","stockNum": 4,"supplyNum": 57,"link": "#","longitude": "119.604368","latitude": "39.945462"},{"id": 4,"name": "苏州**市场","businessScope": "水果咨询服务、代客挑选水果","photo": "https://inews.gtimg.com/om_bt/OY7EgDCa_kppQRisS50oOP_N-sLr0eCG7XByq1ju_altsAA/1000","province": "320000","city": "320500","stockNum": 10,"supplyNum": 154,"link": "#","longitude": "120.442089","latitude": "31.440047"},{"id": 5,"name": "**水果加工市场","businessScope": "制作果汁、果酱、果干等,以满足不同消费者的需求","photo": "https://www.miao-an.com/img/cooperate11.da46bd23.jpg","province": "420000","city": "420100","stockNum": 5,"supplyNum": 4,"link": "#","longitude": "114.303476","latitude": "30.503601"},{"id": 6,"name": "衡水故城县**水果批发市场","businessScope": "提供配送服务,将水果送至客户指定的地点","photo": "https://q9.itc.cn/images01/20240228/3796398619454ec9ad65c0fb33e7363c.jpeg","province": "130000","city": "131100","stockNum": 4,"supplyNum": 0,"link": "#","longitude": "115.879459","latitude": "37.164535"},{"id": 7,"name": "山东临沂华东**水果城","businessScope": "各种水果销售","photo": "https://img2.baidu.com/it/u=2811054594,2149935890&fm=253&fmt=auto&app=120&f=JPEG?w=545&h=500","province": "370000","city": "371300","stockNum": 7,"supplyNum": 1,"link": "#","longitude": "118.343533","latitude": "35.142088"},{"id": 8,"name": "郑州市**水果交易市场 ","businessScope": "水果批发业务,将水果销售给其他商家或餐厅","photo": "https://q6.itc.cn/q_70/images03/20240310/7deaeb3405944bf69773002b8e3af4e7.jpeg","province": "410000","city": "410100","stockNum": 0,"supplyNum": 0,"link": "#","longitude": "113.698629","latitude": "34.702777"},{"id": 9,"name": "**水果礼盒市场","businessScope": "为了满足送礼需求,水果店可以将水果搭配成精美的礼盒,并在礼盒上印制祝福语","photo": "https://ww4.sinaimg.cn/mw690/68d8c97fgy1hr8jw3x753j20ku0rs7an.jpg","province": "210000","city": "210100","stockNum": 0,"supplyNum": 0,"link": "#","longitude": "123.347174","latitude": "41.843021"},{"id": 10,"name": "辽宁**水果基地","businessScope": "水果销售:这是水果店最主要的经营范围,包括各种新鲜水果,如苹果、香蕉、橙子、梨、桃、葡萄等。水果店应该保证水果新鲜、品质优良,以满足消费者的需求","photo": "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage109.360doc.com%2FDownloadImg%2F2024%2F03%2F2010%2F281210346_4_20240320101958209.jpeg&refer=http%3A%2F%2Fimage109.360doc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1731310501&t=aa98bd64ce1b04be69c987fe92037097","province": "130000","city": "130100","stockNum": 0,"supplyNum": 0,"link": "#","longitude": "114.501084","latitude": "38.055933"},{"id": 11,"name": "**水果市场","businessScope": "各种水果销售","photo": "","province": "120000","city": "120100","stockNum": 10,"supplyNum": 20,"link": "#","longitude": "117.333198","latitude": "39.094294"},{"id": 12,"name": "兰州**水果专业市场","businessScope": "种植水果,如草莓、蓝莓等","photo": "https://inews.gtimg.com/om_bt/OSTnVUPg6ncorDwbP4zqi017K1aViojDpPFJJ3Y1x8eEIAA/1000","province": "620000","city": "620100","stockNum": 120,"supplyNum": 103,"link": "#","longitude": "103.776014","latitude": "36.074689"},{"id": 13,"name": "汉中**交易市场","businessScope": "在销售水果的基础上,提供送货上门服务等配送服务","photo": "https://img0.baidu.com/it/u=904203784,1480640225&fm=253&fmt=auto&app=120&f=JPEG?w=750&h=500","province": "610000","city": "610700","stockNum": 0,"supplyNum": 4,"link": "#","longitude": "107.019721","latitude": "33.112655"},{"id": 14,"name": "广东**水果市场","businessScope": "各种新鲜水果,如苹果、梨、草莓、香蕉等销售","photo": "https://copyright.bdstatic.com/vcg/creative/3d3ed3cdbdbca952c43f44a51bc80d20.jpg","province": "440000","city": "440300","stockNum": 0,"supplyNum": 1,"link": "#","longitude": "113.90666","latitude": "22.566552"},{"id": 15,"name": "红宇**水果有限公司","businessScope": "水果销售、水果配送、水果种植等方面","photo": "https://inews.gtimg.com/om_bt/On_IyOQaQwcp76QPnLQJZu67XFp43B6ijaLYxLB-BaMtUAA/1000","province": "440000","city": "441900","stockNum": 0,"supplyNum": 0,"link": "#","longitude": "113.840617","latitude": "22.882198"}]
}
getProvinceClass.json
获取省code数据
{"list": [{"province_code": "110000"},{"province_code": "120000"},{"province_code": "130000"},{"province_code": "140000"},{"province_code": "150000"},{"province_code": "210000"},{"province_code": "220000"},{"province_code": "230000"},{"province_code": "310000"},{"province_code": "320000"},{"province_code": "330000"},{"province_code": "340000"},{"province_code": "350000"},{"province_code": "360000"},{"province_code": "370000"},{"province_code": "410000"},{"province_code": "420000"},{"province_code": "430000"},{"province_code": "440000"},{"province_code": "450000"},{"province_code": "500000"},{"province_code": "510000"},{"province_code": "520000"},{"province_code": "530000"},{"province_code": "610000"},{"province_code": "620000"},{"province_code": "630000"},{"province_code": "640000"},{"province_code": "650000"},{"province_code": "810000"}]
}
getProvinceInfo.json
省份信息弹窗数据
{"data": {"count": 82,"domContent": "<li><a href=\"javascript:void(0);\" οnclick=\"drawProvinceDistribute('130000');\">苹果</a></li>"}
}
7. 备注:页面UI色值参考 TinyVue
- https://opentiny.design/tiny-vue/zh-CN/smb-theme/components/color