腾讯地图城市选择插件-三级联动

城市数据来自于腾讯地图-

腾讯地图api http://lbs.qq.com/webservice_v1/guide-region.html 

1.设计思路

1.因为是传城市ID获取下级城市数据-所以这里做了一个缓存-sessionStorage,就是城市ID来作为KEY值,这样加载过的就可以读取缓存来加载数据了,最新的就去腾讯上面获取数据

2.因为并发限制:5次/秒/接口/Key-所以多个城市一起加载的时候-后面加载的需要延迟一点时间加载(我这里延迟了500)

2.实现接口

 我这里的key使用开放的  key = "WIIBZ-D5F33-ZMD3E-YEOJJ-AMZOS-YKB7K";

 getchildren接口:https://apis.map.qq.com/ws/district/v1/getchildren 

使用jq 的ajax获取数据--下面获取省级数据:

例子1:

$.ajax({
        url: "https://apis.map.qq.com/ws/district/v1/getchildren",
	dataType: "jsonp",
	data: {
	    output: "jsonp",
	    key: key
	},
	cache: false,
	success: function(data) {
		var searchContext = data.result[0];	
		}
	})

那么,获取市级/县级就在以上的例子的data中加多一个id即可

data: {
         output: "jsonp",
	 key: key,
         id:cityId
	},

原理:

1.自定义插件方法

      了解$.fn和$.extend自定义插件

2.三级联动

1.省-》市-》县   2.市-》县   3.县

操作:点击省-》后面联动市和县-

         同理操作 市 就 只联动县  ,

         那么操作县,就停止往下操作

效果图:


代码:

js:

/**
 @Name : QQ腾讯地图 三级联动插件
 @Author: chen RiGuang
 @Date: 2018-07-13
 */
var Storage = window.sessionStorage; 
var key = "WIIBZ-D5F33-ZMD3E-YEOJJ-AMZOS-YKB7K"; 
//省
var $a=1;
(function($) {
	var ms = {
		init: function(obj, args) {
			return(function() {
				if($a==1){
					//腾讯地图单个key每秒最高5次,多个地图插件同时使用时延迟实例创建执行
					ms.AllprovinceData(obj, args);
				   ms.bindEvent(obj, args);
				   $a++;
				}else{
					setTimeout(function(){
						ms.AllprovinceData(obj, args);
				   ms.bindEvent(obj, args);
					},500)
				}
			})();
		},
		//省数据
		AllprovinceData: function(obj, args) {
			return(function() {
				var searchContext = Storage.getItem("provinceData");
				if(searchContext != null) {
					searchContext = JSON.parse(searchContext);
					ms.AllprovinceHtml(obj, args, searchContext)
				} else {
					$.ajax({
						url: "https://apis.map.qq.com/ws/district/v1/getchildren",
						dataType: "jsonp",
						data: {
							output: "jsonp",
							key: key
						},
						cache: false,
						success: function(data) {
							var searchContext = data.result[0];
							Storage.setItem("provinceData", JSON.stringify(data.result[0]));
							ms.AllprovinceHtml(obj, args, searchContext)
						}
					})
				}
			})();
		},
		//回填省HTML
		AllprovinceHtml: function(obj, args, searchContext) {
			var CityHtml = '<div class="selectCity"><div class="selectTest"></div>' +
				'<div class="iconDown"></div>' +
				'</div>' +
				'<div class="selectTestBox">' +
				'<ul class="ub-fh"></ul>' +
				'</div>';
			var cityBox = '<div class="clear">' +
				'<div name="' + args.provinceId + '" class="' + args.provinceId + '  countryTd">' + CityHtml + '</div>' +
				'<div name="' + args.cityId + '" class="' + args.cityId + ' countryTd">' + CityHtml + '</div>' +
				'<div name="' + args.districtId + '" class="' + args.districtId + ' countryTd">' + CityHtml + '</div>' +
				' </div>';
			obj.append(cityBox);
			var listLi = '<li class="listSelect"></li>';
			var ifSetCity = false;
			$.each(searchContext, function(i, n) {
				var $clone = $(listLi).clone();
				$clone.text(n.fullname);
				$clone.attr("id-value", n.id);
				$clone.attr("name", n.fullname);
				if(n.fullname == args.province) {
					ifSetCity = true;
					$clone.addClass('active-this');
					obj.find("." + args.provinceId + ' .selectTest').attr("pid", n.id);
				}
				obj.find("." + args.provinceId + ' ul').append($clone);
			})
			if(ifSetCity) {
				obj.find("." + args.provinceId + ' .selectTest').attr("title",args.province);
				obj.find("." + args.provinceId + ' .selectTest').text(args.province);
			} else {
				obj.find("." + args.provinceId + ' ul li').eq(0).addClass("active-this");
				obj.find("." + args.provinceId + ' .selectTest').text(obj.find("." + args.provinceId + ' ul li').eq(0).text());
				obj.find("." + args.provinceId + ' .selectTest').attr("pid", obj.find("." + args.provinceId + ' ul li').eq(0).attr("id-value"));
			}
			var provincePid = obj.find("." + args.provinceId + ' .selectTest').attr("pid");
			ms.AllCityData(obj, args, provincePid, 1)
		},
		//市-县数据
		AllCityData: function(obj, args, cityid, $ide) {
			return(function() {
				var searchContext = Storage.getItem(cityid);
				if(searchContext != null) {
					var cityData = JSON.parse(searchContext)
					ms.AllCityHtml(obj, args, cityData, $ide)
				} else {
					$.ajax({
						url: "https://apis.map.qq.com/ws/district/v1/getchildren",
						dataType: "jsonp",
						data: {
							output: "jsonp",
							key: key,
							id: cityid
						},
						cache: false,
						success: function(data) {
							if(data.message == "错误的id") {return;} else if(data.message=="此key每秒请求量已达到上限"){
								 location.reload();
							}else{
								Storage.setItem(cityid, JSON.stringify(data.result[0]));
								var cityData = data.result[0];
								ms.AllCityHtml(obj, args, cityData, $ide);
							}
						}
					})
				}
			})();
		},
		//回填市县数据
		AllCityHtml: function(obj, args, cityData, $ide) {
			return(function() {
				var nameId = "";
				var $name = "";
				if($ide == 1) {
					nameId = args.cityId;
					$name = args.city;
				} else if($ide == 2) {
					nameId = args.districtId;
					$name = args.district;
				}
				var listLi = '<li class="listSelect uinn-l"></li>';
				var ifSetCity = false;
				$.each(cityData, function(i, n) {
					var $clone = $(listLi).clone();
					$clone.text(n.fullname);
					$clone.attr("id-value", n.id);
					$clone.attr("name", n.fullname);
					if(n.fullname == $name) {
						ifSetCity = true;
						$clone.addClass('active-this');
						obj.find("." + nameId + ' .selectTest').attr("pid", n.id);
					}
					obj.find("." + nameId + ' ul').append($clone);
				})
				if(ifSetCity) {
					obj.find("." + nameId + ' .selectTest').text($name);
					obj.find("." + nameId + ' .selectTest').attr("title",$name);
				} else {
					obj.find("." + nameId + ' ul li').eq(0).addClass("active-this");
					obj.find("." + nameId + ' .selectTest').text(obj.find("." + nameId + ' ul li').eq(0).text());
					obj.find("." + nameId + ' .selectTest').attr("title",obj.find("." + nameId + ' ul li').eq(0).text());
					obj.find("." + nameId + ' .selectTest').attr("pid", obj.find("." + nameId + ' ul li').eq(0).attr("id-value"));
				}
				var provincePid = obj.find("." + nameId + ' .selectTest').attr("pid");
				if($ide == 1) {
					ms.AllCityData(obj, args, provincePid, 2)
				} else if($ide == 2) {
					
					var province = obj.find("." + args.provinceId + ' .selectTest').text();
					var city = obj.find("." + args.cityId + ' .selectTest').text();
					var district = obj.find("." + args.districtId + ' .selectTest').text();
					var selectDATA = {
						province: province,
						city: city,
						district: district
					}
					args.backFn(selectDATA);
				}
			})();
		},
		//绑定事件
		bindEvent: function(obj, args) {
			return(function() {
				// 空白事件
				$(document).click(function(e) { // /父区域 居住地select显示隐藏
					$.each($('.countryTd'), function(i, n) {
						var _con = $(n);
						if(!_con.is(e.target) && _con.has(e.target).length === 0) {
							_con.find('.selectTestBox').hide(); // 空白事件
						}
					})
				})
				// 点击城市框
				obj.on("click",".selectCity",function(){
					var countryTd = $(this).parents(".countryTd").attr("name");
					var _thisId = obj.find("." + countryTd);
					if($(this).siblings(".selectTestBox").is(":hidden")) {
						_thisId.find(".selectTestBox").show();
					} else {
						_thisId.find(".selectTestBox").hide();
					}
				})
				// 选中城市下拉
				obj.on("click",".listSelect",function(){
					var test = $(this).text();
					var $id = $(this).attr("id-value");
					var countryTd = $(this).parents(".countryTd").attr("name");

					var _thisId = obj.find("." + countryTd);
					$(this).addClass("active-this").siblings().removeClass("active-this");
					obj.find(".selectTestBox").hide();
					if(test != _thisId.find('.selectTest').text()) {
						_thisId.find('.selectTest').text(test);
						_thisId.find('.selectTest').attr("title",test);
						if(countryTd == args.provinceId) {
							//省
							obj.find('.' + args.cityId+" "+"ul").html("");
							obj.find('.' + args.districtId+" ul").html("");
							ms.AllCityData(obj, args, $id, 1);

						} else if(countryTd == args.cityId) {
							//市
							obj.find('.' + args.districtId +" ul").html("");
							ms.AllCityData(obj, args, $id, 2)
						}
					}

				})

			})();
		}
	}
	$.fn.createPage = function(options) {
		var args = $.extend({
			provinceId: "province",
			cityId: "city",
			districtId: "district",
			province: '广东省',
			city: '广州市',
			district: '天河区',
			backFn: function() {}
		}, options);
		ms.init(this, args);
	}
})(jQuery)

html:

<!DOCTYPE html>
<html>

	<head>

		<head>
			<meta charset="UTF-8">
			<title></title>
		</head>
		<style type="text/css">
			*{ padding: 0; margin: 0; }
			ol, ul,li { list-style: none; }
			.box{
				width: 500px;
				margin: 20px auto;
			}
			#city2{
				margin-top: 20px;
			}
			.clear:after {
				visibility: hidden;
				clear: both;
				display: block;
				width: 0;
				height: 0;
				content: ".";
			}
			
			.selectTestBox {
				max-height: 200px;
				overflow: auto;
				border: 1px solid #e1e1e1;
				position: absolute;
				z-index: 666;
				left: 0;
				display: none;
				cursor: pointer;
				background: #FFFFFF;
				width: 100%;
			}
			
			.selectCity {
				height: 36px;
				line-height: 36px;
				overflow: hidden;
				background: #F5F5F5;
				position: relative;
			}
			
			.selectTest {
				padding: 0 20px 0 10px;
				max-width: 100%;
				height: 100%;
				cursor: pointer;
			}
			
			.listSelect {
				min-height: 36px;
				line-height: 36px;
				padding-left: 10px;
			}
			
			.listSelect:hover {
				background: #ececec;
				color: #000000;
			}
			
			.active-this,
			.active-this:hover {
				background: #33bb67;
				color: #FFFFFF;
			}
			
			.iconDown {
				background: url(icon_more_bottom.png) no-repeat center;
				right: 5px;
				top: 0px;
				z-index: 2;
				width: 10px;
				height: 100%;
				position: absolute;
			}
			
			.countryTd:first-child+.countryTd {
				margin: 0 20px;
			}
			
			.countryTd {
				width: 150px;
				position: relative;
				float: left;
			}
		</style>

		<body>
			<div class="box">
				<div id="city1"></div>
				<div id="city2"></div>
			</div>

		</body>
		<script src="jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
		<script src="TXCity-min.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			$("#city1").createPage({			
				province: '广东省',
				city: '广州市',
				district: '天河区',
				backFn: function(data) {
					console.log(data)
				}

			});
			$("#city2").createPage({				
				province: '广东省',
				city: '深圳市',
				district: '罗湖区',
				backFn: function(data) {
					console.log(data)
				}
			});
		</script>
</html>

使用方法:

$("#city2").createPage({		
		province: '广东省',
		city: '深圳市',
		district: '罗湖区',
		backFn: function(data) {
		console.log(data)
	}
});

新手上路,不喜勿喷

不喜欢复制粘贴的豪哥们看这里,直接下载源码:https://download.csdn.net/download/m0_37596829/10543648

代码繁琐-跪求路过大神指点一下萌新--嘤嘤嘤嘤

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页