Nonsense begins: the use of Gaode map to achieve administrative area color marking and prompt text, so, a simple package.

I. Introduction of main functions

1. Date is optional. Modified Date Modified the search criteria.

2, price threshold display.

3. The search area is filled and marked according to the filling color inferred from the value.

4. Refresh and modify map scale operation.

Two, the entry code

Take a quick look at the entry code:

$mapoption.initmap ('container'). SearchMap (function(){return [{name:"张 大 口",score:1690}, {name:"张 大 口",score: 290}, {name: "hefei", score: 690}, {name: "gansu," score: 9000}, {name: "shijiazhuang", score: 987}, {name: "zaozhuang," score: 7622}, {name: "chengde," score: 922}, {name: "changchun", score: 1922}]}) setSegmentControl (function (segmentControlSelectIndex) {/ / js triggering time selector});Copy the code

$mapOption is set as a window property so it can be called directly.

The entry code is as simple as passing in a closure, a closure that returns a set of administrative region names and numeric objects, and searching and rendering the map inside highly encapsulated.

Three, function realization

html

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="Initial - scale = 1.0, the user - the scalable = no"> 
		<title></title>
		<script type="text/javascript" src="Https://webapi.amap.com/maps?v=1.4.15&key=83bc36d34f * * * * * * * * * * 5650 e518f & plugin = AMap. DistrictSearch, AMap. DistrictLayer"></script>
		<script src="./GDMapWeb.js"></script>
	    <link rel="stylesheet" type="text/css" href="./GDMapWeb.css"/>
	</head>
	<body>
		<div style="position: relative;"id="contentView">
			<! - map -- -- >
			<div id="container"></div> 
			<! -- Pointer -->
			<div class="indicator">
				<div style="text-align: left; The font - size: 0.75 rem; Margin - top: 0.3125 rem; Margin - left: 0.1875 rem; Margin - bottom: 0.625 rem.">Increase the value</div>
				<div id="indicator" style="width: 100%">
				</div>
			</div>
			<! -- Data display -->
			<div class="scoreBar">
				<div style="width: 32%; height: 100%; float: left; position: relative;">
					<div style="width: 100%; margin-top: auto; margin-bottom: auto; position: relative; top:50%; transform:translate(0,-50%);">
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;">Average price</p>
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;" id="averageScoreLab">0</p>
					</div>
				</div>
				<div style="float: left; Width: 0.0625 rem; height: 70%; background-color: lightgray; position: relative; top:50%; transform:translate(0,-50%);"></div>
				<div style="width: 32%; height: 100%; float: left; position: relative;">
					<div style="width: 100%; margin-top: auto; margin-bottom: auto; position: relative; top:50%; transform:translate(0,-50%);">
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;">The highest</p>
						<p style="text-align: center; The font - size: 0.75 rem; color: black;" id="maxScoreCityLab">-</p>
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;" id="maxScoreLab">0</p>
					</div>
				</div>
				<div style="float: left; Width: 0.0625 rem; height: 70%; background-color: lightgray; position: relative; top:50%; transform:translate(0,-50%);"></div>
				<div style="width: 32%; height: 100%; float: left; position: relative;">
					<div style="width: 100%; margin-top: auto; margin-bottom: auto; position: relative; top:50%; transform:translate(0,-50%);">
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;">The lowest price</p>
						<p style="text-align: center; The font - size: 0.75 rem; color: black;" id="minScoreCityLab">-</p>
						<p style="text-align: center; The font - size: 0.75 rem; color: darkgray;" id="minScoreLab">0</p>
					</div>
				</div>
			</div>
			<! -- Year month day selector -->
			<div class="segmentControl" id="segmentControl">
				<div class="segmentControlItem">day</div>
				<div class="segmentControlSep"></div>
				<div class="segmentControlItem" >weeks</div>
				<div class="segmentControlSep"></div>
			    <div class="segmentControlItem">month</div>
			</div>
			<! -- Display time -->
			<div id="showDateInfo"></div>
			<! -- Scale -->
			<div class="mapScale">
				<div class="mapScaleItem">+</div>
				<div style="position: absolute; Height: 0.0625 rem; width: 96%; margin-left: 2%; margin-right: 2%; background-color: #DCDCDC;"></div>
				<div class="mapScaleItem">-</div>
			</div>
			<! - search - >
			<div class="mapReload"><img src="./images/shuaxin.png" ></div>
			<! -- -->
		</div>
	</body>
	<script>
		 // Initialize the map
		 $mapOption.initMap('container').searchMap(function(){
			 return[{name:zhangjiakou.score:1690},
		 {name:"Shaanxi".score:290},
                 {name:Hefei "".score:690},
		 {name:"Gansu".score:9000},
		 {name:"Shijiazhuang".score:987},
		 {name:Zaozhuang "".score:7622},
		 {name:"Chengde".score:922},
		 {name:"Changchun".score:1922}]
		 })
		 .setSegmentControl(function(segmentControlSelectIndex){
			 //js triggers the time selector
		 });

	</script>
</html>
Copy the code

CSS

* {padding:0px;
	    margin:0px;
	}
	#headerConditon{
		width: 100%;
		height: 2.8125 rem;
		position: relative;
	}
	.headerConditonItem {
		width: 50%;
		background-color: #1E90FF;
	}
	
	.headerConditonItem div {
		display: flex;
		align-items: center;
		justify-content: space-around;
		flex-direction: row;
		font-size: 0.875 rem;
	}
	
	.headerConditonItem img {
		width: 0.9375 rem;
		height: 0.9375 rem;
		display: flex;
		align-items: center;
		justify-content: space-around;
		flex-direction: row;
		
	}
	#container {width:100%; height: 100%; }.showInfoLab {
		height: 25px;
		width: 100px;
		display: inline-block;
	}
	.pointShowInfoLab {
		width: 5px;
		height: 5px;
		border-radius: 2.5 px.;
		background-color: black;
		margin-top: 12.5 px.;
		display: inline-block;
		float: left;
	}
	.areaShowInfoLab {
		font-size: 0.3 rem;
		height: 50%;
	}
	.indicator {
		position: absolute;
		left: 0.625 rem;
		top: 0.625 rem;
		width: 5.5 rem;
		background-color: white;
		box-shadow: -2px 0px 5px 1px #DCDCDC.0px -2px 5px 1px #DCDCDC.2px 0px 5px 1px #DCDCDC.0px 2px 5px 1px #DCDCDC;
	}
	
	.scoreBar {
		position: absolute;
		left: 0.625 rem;
		bottom: 1.875 rem;
		height: 3.125 rem;
		width: 11.25 rem;
		background-color:rgba(255.255.255.0.75);
		border-radius: 0.3125 rem;
		box-shadow: -2px 0px 5px 1px #DCDCDC.0px -2px 5px 1px #DCDCDC.2px 0px 5px 1px #DCDCDC.0px 2px 5px 1px #DCDCDC;
	}
	
	.segmentControl {
		position: absolute;
		right: 0.625 rem;
		top: 0.625 rem;
		/ * width: 8.125 rem; * /
		height: 1.875 rem;
		background-color: white;
		border-radius: 0.25 rem;
		border: solid 0.0625 rem rgba(111.165.235.1.0);
	}
	
	#showDateInfo{
		position: absolute;
		right: 2rem;
		top: 2.9 rem;
		color: # 555555;
		visibility:hidden;
		height: 1.25 rem;
		line-height: 1.25 rem;
	}
	
	.segmentControlItem {
		height: 100%;
		width: 2.1875 rem;
		line-height: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		flex-direction: column;
		float: left;
		text-align: center;
		position: relative;
		top:50%;
		transform:translate(0, -50%);
		z-index: 0;
	}
	
	.segmentControlSep {
		float: left;
		width: 0.0625 rem;
		background-color: rgba(111.165.235.1.0);
		height: 100%;display: inline-block;
	}
	
	.mapScale {
		position: absolute;
		right: 0.625 rem;
		bottom: 0.625 rem;
		width: 2.0 rem;
		height: 4.5 rem;
		border-radius: 0.3125 rem;
		background-color: white;
		box-shadow: -2px 0px 5px 1px #DCDCDC.0px -2px 5px 1px #DCDCDC.2px 0px 5px 1px #DCDCDC.0px 2px 5px 1px #DCDCDC;
	}
	
	.mapScaleItem {
		width: 100%;
		height: 50%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		flex-direction: row;
	}
	
	.mapReload{
		position: absolute;
		right: 1.025 rem;
		bottom: 6rem;
		width: 1.2 rem;
		height: 1.2 rem;
		border-radius: 0.6 rem;
		background-color: white;
		text-align: center;
		vertical-align: middle;
		-webkit-transition: width 2s, height 2s, -webkit-transform 2s; /* For Safari 3.1 to 6.0 */
		transition: width 2s, height 2s, transform 2s;
	}
	
	.mapReload img {
		width: 80%;
		height: 80%;
		position: relative;
		top:50%;
		transform:translate(0, -50%);
	}
Copy the code

JS

(function(window){
	var indicators = [2000.800.500]
	var colors = ['rgba (208,53,37,1.0)'.'rgba (244181180,1.0)'.'rgba (180216143,1.0)'.'rgba(93,169,60,1.0)']
	var district = null; 
	var startDeg = 0;// Refresh button rotation Angle
	var mapOption = {}// Manipulate map objects
	mapOption.map = null// Map object
	mapOption.mapZoom = 4 // Map default scale level
	mapOption.areas = null
	mapOption.date = new Date()
	mapOption.scoreCallBack = null// Calculate the threshold external callback closure
	
	// Administrative region configuration
	var disCountry = new AMap.DistrictLayer.Country({
	    zIndex:10.SOC:'CHN'.depth:1.// Set the display level to 1, so that only provincial level is displayed
	    styles: {// Line style
	        'nation-stroke':'# 000000'./ / line
	        'coastline-stroke':'# 888888'./ / the coastline
	        'province-stroke':'# 888888'.// Provincial margin
	        'fill':'rgba (245245245,1.0)'}})// Initialize the map
	mapOption.initMap = function(el){
		mapOption.map = new AMap.Map(el,{
			zoom:mapOption.mapZoom,/ / level
			center: [116.397428.39.90923].// Map initializes the central latitude and longitude
			showLabel:false.// Do not display default annotations
			mapStyle:'amap://styles/7e862995ee18*********07edbd958'.// (replace the current account) load map style, which can be modified in the autonavi account background, remove other rendering conditions, only keep the gray map
			layers:[disCountry],// Fill the style
			viewMode:'2D'});this.map.on('zoomend'.function(ev) {
			// When the map scale changes, get the current map scale
			mapOption.mapZoom = mapOption.map.getZoom();
		})
		
		// Display tags
		var main = document.getElementById('contentView');
		// Set width and height
		main.style.width = window.innerWidth + 'px';
		main.style.height = window.innerHeight + 'px';
		// Add a color index indicator
		this.initIndicator()
		// Add the function of modifying map scale
		this.changeMapScale()
		// Add the refresh map animation function
		this.addReloadAnimationAction()
		return this;
	}
	
	/ / search
	mapOption.searchMap = function(areas){
		this.areas = areas
		for (var i= 0; i < areas().length; i++) {var area = areas()[i];
			this.startSearchMap(area);
		}
		// Calculate some thresholds
		this.getShowScoreData(function(average,maxCity,minCity,max,min){})
		return this;
	}
	// Start searching one by one
	mapOption.startSearchMap = function(area){
		var that = this;
		if(! district){ district =new AMap.DistrictSearch({
			    // return administrative boundary coordinates and other specific information
			    extensions: 'all'.// Set the query administrative level to district
			    level: 'district'.subdistrict: 0})}// Search for administrative boundaries by name
		district.search(area.name, function(status, result) {
		   var bounds = result.districtList[0].boundaries// Administrative boundaries
		   var center = result.districtList[0].center// Administrative center (e.g., provincial capital city)
		   //console.log(JSON.stringify(center));
		   that.addMark(center,{name:area.name,score:area.score});
		   if (bounds) {
		     for (var i = 0, l = bounds.length; i < l; i++) {
		      // Generate an administrative district polygon
		      var polygon = new AMap.Polygon({
		        map: that.map,
		        strokeWeight: 0.3.path: bounds[i],
		        fillOpacity: 0.7.fillColor: that.judgeScoreGetCoror(area.score),// Get the fill color based on the value
		        strokeColor: '# 888888'.// The boundary color})}}})}// Add annotations
	mapOption.addMark = function(position,info){
		var marker = new AMap.Marker({
		        // Dot marks the position displayed on the map
		        position: [position.lng, position.lat],
		        			 offset:new AMap.Pixel(0, -15),// Adjust the offset position of the annotation
		        			 content: '<div class="showInfoLab">' +
		                 '
      
'
+ '<span class="pointShowInfoLab">' + '</span>' + '</div>' + '
'
+ '<div class="areaShowInfoLab">'+info.name +'</div>' + '<div class="areaShowInfoLab">'+info.score +'</div>' + '</div>' + '</div>' }); // Specify target display map for Marker. When parameter value is null, remove current Marker: setMap(NULL) marker.setMap(this.map); } // Get the current fill color value mapOption.judgeScoreGetCoror = function(score){ var color = colors[colors.length - 1] var minScore = indicators[indicators.length - 1] var maxScore = indicators[0] if(score > maxScore) { return colors[0]}else if(score < minScore) { return color } else { for(var i = 0; i < indicators.length; i++){var currentScore = indicators[i]; if(score < currentScore && score >= indicators[i + 1]) { color = colors[i + 1]; break}}}return color } // Initialize the indicator mapOption.initIndicator = function (){ var content = '>' + indicators[0]; var color = colors[0]; var indicatorHtml = this.indicatorCell(color,content,false) for (var i = 1; i < indicators.length; i++) { color = colors[i]; content = indicators[i] +'~' + indicators[i - 1] indicatorHtml += this.indicatorCell(color,content,false) } content = '<' + indicators[indicators.length - 1] color = colors[colors.length - 1]; indicatorHtml += this.indicatorCell(color,content,true) var indicator = document.getElementById('indicator') indicator.innerHTML = indicatorHtml; return this; } mapOption.indicatorCell = function(color,content,isLast){ return '+ (isLast ? 'margin - bottom: 0.1875 rem;" ' : '"') + '>' +'+ color +'; Margin - left: 0.1875 rem; display: inline-block; position: relative; top: 50%; Margin - top: 0.5 rem;" >' +'< div style = "font, size: 0.8 rem; color:#333333; Margin - left: 0.3125 rem; float: left; Height: 1.5625 rem; position: relative; top: 50%; Margin - top: 0.78125 rem. The line - height: 1.5625 rem." > '+ content +'</div>' +'</div>' } // Average, highest, lowest mapOption.getShowScoreData = function(callBack){ this.scoreCallBack = callBack; var average = 0; var max = 0; var min = 0; var maxCity = ' '; var minCity = ' '; var areasData = this.areas(); for(var i = 0; i < areasData.length; i++){var currentScore = areasData[i].score; var currentName = areasData[i].name; average += currentScore; if(i == 0){ max = currentScore; maxCity = currentName; min = currentScore; minCity = currentName; } else { var currentMax = max < currentScore ? currentScore : max; maxCity = max < currentScore ? currentName : maxCity; max = currentMax; var currentMin = min > currentScore ? currentScore : min; minCity = min > currentScore ? currentName : minCity; min = currentMin; } } average = (average / areasData.length).toFixed(2); // The purpose of object storage is to expose external parameters as closures, but nothing else this.scoreCallBack(average,maxCity,minCity,max,min); // Set the threshold mapOption.setHtml('averageScoreLab',average) mapOption.setHtml('maxScoreCityLab',maxCity) mapOption.setHtml('minScoreCityLab',minCity) mapOption.setHtml('maxScoreLab',max) mapOption.setHtml('minScoreLab',min) return this } // Set DOM content encapsulation mapOption.setHtml = function(el,content){ var element = document.getElementById(el) element.innerHTML = content } // Set the date picker segmentControl switch event mapOption.setSegmentControl = function(selectCallBack){ var that = this; var items = document.getElementsByClassName("segmentControlItem") for(var i = 0; i < items.length; i++){var item = items[i]; item.index = i; item.onclick = function (){ var segmentControl = document.getElementById('segmentControl'); if(segmentControl.selectIndex ! =this.index){ that.selectChangeStyle(this.index); selectCallBack(this.index); }}if(i == 0){ that.selectChangeStyle(0); } var borderRadius = ' ' var padding = ' ' if(i == 0) { borderRadius = '0.25 rem 0 0 0.25 rem' padding = '0' } else if(i == items.length - 1) { borderRadius = '0 0.25 rem 0.25 rem 0' padding = '0' } else { borderRadius = '0 0 0 0' padding = '0. } item.style.borderRadius = borderRadius item.style.padding = padding } return this; } mapOption.selectChangeStyle = function(index){ var items = document.getElementsByClassName("segmentControlItem") for(var i = 0; i < items.length; i++){var item = items[i]; item.style.backgroundColor = (i == index) ? 'rgba (235243254,1.0)' : 'rgba (255255255,)'; item.style.color = (i == index) ? 'rgba (111165235,1.0)' : '#DCDCDC'; } var segmentControl = document.getElementById('segmentControl'); segmentControl.selectIndex = index; } mapOption.selectSegmentControl = function(index){ var showDateInfoDiv = document.getElementById('showDateInfo'); showDateInfoDiv.style.visibility = index == 0 ? 'hidden' : 'visible'; var dateInfo = ' '; if(index == 1) {// Count sunday-Saturday as a cycle // Get the first day of the week var weekFirstDay = new Date(this.date- (this.date.getDay()) * 86400000) // Get the month in which the week begins var firstMonth = Number(weekFirstDay.getMonth()) + 1 // Get the last day at the end of the week var weekLastDay = new Date((weekFirstDay / 1000 + 6 * 86400) * 1000) // Gets the month at the end of the week var lastMonth = Number(weekLastDay.getMonth()) + 1 dateInfo = firstMonth + The '-' + weekFirstDay.getDate() + '~' + lastMonth + The '-' + weekLastDay.getDate() } else if(index == 2) { // Get the month of the day var weekFirstDay = new Date(this.date) var firstMonth = Number(weekFirstDay.getMonth()) + 1 dateInfo = weekFirstDay.getFullYear() + 'years' + firstMonth + 'month' } showDateInfoDiv.innerHTML = dateInfo; } // Modify the selection date mapOption.changeSearchDate = function(newDate){ var segmentControl = document.getElementById('segmentControl'); this.date = new Date(newDate); this.selectSegmentControl(segmentControl.selectIndex); } // Change the map scale mapOption.changeMapScale = function(){ var items = document.getElementsByClassName("mapScaleItem") var that = this; for(var i = 0; i < items.length; i++){var item = items[i]; item.index = i; item.onclick = function (){ if(this.index == 0) { if(that.mapZoom < 7) {// Adjust the map scale that.map.setZoom(that.mapZoom += 1); }}else { if(that.mapZoom > 4.5) {// Adjust the map scale that.map.setZoom(that.mapZoom -= 1); }}}}return this; } // Add spin refresh animation mapOption.addReloadAnimationAction = function (){ var item = document.getElementsByClassName("mapReload") [0]; var that = this; item.onclick = function (){ startDeg += 360; this.style.transform = 'rotate('+startDeg+'deg)'; mapOption.map.destroy(); mapOption.initMap('container') .searchMap(that.areas)// Re-search .getShowScoreData(function(average,maxCity,minCity,max,min){}); var segmentControl = document.getElementById('segmentControl'); window.webkit.messageHandlers.chageDateJS.postMessage(segmentControl.selectIndex); } return this; } window.$mapOption = mapOption; }) (window) Copy the code

Bad code, don’t spray, learn from each other and improve [fist][fist][fist]