preface

The main business I am responsible for in the company is GIS development. Now I am using Baidu Map. Compared with Autonavi, Baidu Map is always slow and slow, so I came up with this plan. To achieve a library of their own, you can quickly switch between Baidu map and Gaode map.

Train of thought

With the above requirement, we are thinking about the function points involved in the requirement and how to implement it.

One: configuration item, one-click configuration can select load. For example, mapType =1: load Baidu Map, mapType =2: load Autonavi ii: How does Baidu smoothly switch to Autonavi III: how does the constructor provided by Baidu compatible with the method under MapCopy the code

The architecture

With the above requirements and ideas, the next is to use the code to achieve, first of all, I think, since it is a library, it must avoid global variable pollution, and is extensible, the overall performance of the code to be high.

/** * Author: [email protected] * Time: 2018-03-14 * Description: Baidu and AmAP simple package to achieve fast switching * Version: 1.0.0.1 ** */; (function() {'use strict';
	var arg = arguments,
		win = arg[0] || window,
		mapLsit = arg[1] || [];
		
})(window,[function(){
	
},function(){
	
}]);
Copy the code

The above schema is just an immediate function with two arguments, the first being the window object and the second being an array containing two functions. The first function is // Baidu map related method encapsulation, the second function is // Autonavi map related method encapsulation, maybe in the future, there are Tencent map encapsulation. So this can be easily extended.

The overall code

This is the overall code design, the code is not very perfect, some controls need to be packaged separately into a tool, some Baidu map provided by the plug-in Autonavi did not provide, need their own handwriting. For example, the following have their own handwriting on the map to pull the box to search. After pulling the box triggers a callback, return to the location of the box you pulled, you can handle your related operations in the callback.

/** * Author: [email protected] * Time: 2018-03-14 * Description: Baidu and AmAP simple package to achieve fast switching * Version: 1.0.0.1 ** */; (function() {
	'use strict'; var arg = arguments, win = arg[0] || window, mapLsit = arg[1] || []; //console.log(mapLsit); /** */ var map = win.gis_map = {}; /** * config item ** / map.config = {mapType: 0, //0: represents Baidu map, 1: Autonamap, 2: Tencent map}; // All methods after the map instance map.pulic = {}; /** */ map.init =function() { main(); }; /** * Load the corresponding map according to the configuration file selection ** */function main() {

		switch(map.config.maptype) {
			case 0:
				casemap(0);
				break;
			case 1:
				casemap(1);
				break;
			case 2:
				casemap(2);
				break; default: }; /** * select load * @n {number} load map by type ** */function casemap(n) {
			var fn = null;
			if(mapLsit.length) {
				fn = mapLsit[n];
				mapLsit = null;
				fn.call(map);
				//console.log(fn.call(map),'Loading Baidu Map successful! '); }}} @n {number} 0: represents Baidu map, 1: represents Gaord map ** / map.setpulic =function(n) {
		var map_pulic = this.pulic;
		if(n === 0) {

		} else if(n === 1) {// Compatible Gaode set center point and zoom size /** * @point {point} point * @level {number} zoom level ** / map_pulic. CenterAndZoom =function(point, level) { this.setZoomAndCenter(level, point); } / enable zoom * * * * * * / map_pulic enableScrollWheelZoom =functionMap_pulic. AddEventListener = map_pulic. On; Map_pulic. AddOverlay = map_pulic. Add; Map_overlay. RemoveOverlay = map_overlay. Remove; Map_pulic. getDistance= // Close the window window map_pulic.closeInfoWindow = map_pulic.clearInfoWindow; /** * Map latitude and longitude coordinates to the plane map pixel coordinates * lnglatToPixel * @point {point} point ** / map_pulic.pointtopixel =function(point) {
				returnmap_pulic.lnglatToPixel(point, 10); } /** * get the distance between two points * @start {Point} end {Point} end ** / map_pulicfunction(start, end) {
				return start.distance(end);
			}
		}
		//console.log(map_pulic,'map_pulic');

	}

})(window, [function() {
	'use strict'; // Baidu map related method encapsulationif(! BMap) { console.error('Please check whether the config item and the js loaded map are correct! ');
		return; } / / var _toString = validation data type Object. The prototype. ToString; /** * Create the Map instance in the specified container, after which you need to call the map.centerandZoom () method to initialize the Map. Initialized not map will not be able to do anything * @ container {String | HTMLElement} * @ opt {* attribute types describe minZoom Number shows the minimum level of map permits maxZoom Number MapType indicates the maximum level of a map. MapType indicates the mapType. The default value is BMAP_NORMAL_MAPenableHighResolution Boolean Specifies whether to enable the use of high-resolution maps. On iPhone4 and later devices, you can enable this option to obtain a higher resolution base image. This option is disabled by default for v1.2 and v1.3, and enabled for v1.4enableAutoResize Boolean Specifies whether to automatically adapt to map container changes. Enabled by defaultenableMapClick Boolean Specifies whether base Map clickable function is enabled. PanOptions *} is enabled by default. This class indicates optional parameters of the Map constructor. It has no constructor, but can be represented as an object literal. * */ this.Map =function(container, opt) { var that = this.pulic = new BMap.Map(container, opt); // Trigger the instance method to override this.setpulic(0);returnthat; } @lng {Number} latitude ** @lat {Number} latitude ** / this.point =function(lng, lat) {
		returnnew BMap.Point(lng, lat); @center {Point coordinate Point} creates a geographic Point coordinate with the specified longitude and latitude * @radius {Number} radius units in meters * @opts {* strokeColor String FillColor String Indicates the filling color of the circle. StrokeWeight Number Specifies the width of the circular border, in pixels. StrokeOpacity Number specifies the opacity of the circular border. The value range is 0-1 fillOpacity Number Specifies the opacity of the circular padding. Value range: 0-1 strokeStyle String Indicates the pattern of the circle edge, which can be solid or consistentenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
		enableEditing Boolean Whether line Editing is enabled. Default isfalse
		enable1, Send Boolean Whether to respond to click events. Defaulttrue
	 * }
	 * 
	 * */
	this.Circle = function(center, radius, opts) {
		returnnew BMap.Circle(center, radius, opts); } /** * create an image annotation instance. * @point {point coordinates point} creates a geographic point coordinate at the specified latitude and longitude * @opts {* offset Size specifies the offset of the annotation position icon icon used for the annotation objectenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
		enableDragging Boolean Whether drag is enabled, default isfalse
		enable4. Send Boolean Whether to respond to click events. The default istrueRaiseOnDrag Boolean Whether the annotation is enabled to leave the map surface effect when dragging and dropping the annotation. The default isfalseDraggingCursor String Style of the mouse pointer when dragging a cursor. Rotation Number Rotation Angle Shadow Icon Shadow Icon Title String Display content when the mouse moves to the marker *} * */ this.marker =function(point, opts) {
		returnnew BMap.Marker(point, opts); } @points {Array<Point>} @opts {* strokeColor String strokeWeight Number Width of the line, StrokeOpacity Number Specifies the transparency of the curve, in pixels. The value ranges from 0 to 1. StrokeStyle String Specifies the pattern of the curve, which is solid or consistentenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
		enableEditing Boolean Whether line Editing is enabled. Default isfalse
		enable1, Send Boolean Whether to respond to click events. DefaulttrueICONS Array<IconSequence> configures the ICONS that fit the Polyline *} * */ this.polyline =function(points, opts) {
		returnnew BMap.Polyline(points, opts); } /** * Creates an icon object instance with the given image address and size * @URL {String} URL address * @size {size} size * @opts {* Anchor Size The anchor point of the icon. This point is used to determine the location of the icon. It is the offset from the upper left corner of the icon, which by default is equal to the middle of the icon width and height. ImageOffset Size Specifies the offset of the image from the viewable area. When the information window is opened, the position of the sharp corner at the bottom of the information window relative to the upper left corner of the icon is equal to the anchor of the icon by defaultprintImageUrl String is used for printed images. This property only works with IE6, to solve the problem of IE6 printing incorrectly with filters *} * */ this.icon =function(url, size, opts) {
		returnnew BMap.Icon(url, size, opts); } /** * create a rectangular area Size object with the specified width and height * @width {Number} horizontal * @height {Number} vertical ** / this.size =function(width, height) {
		returnNew map.size (width, height)} /** * Autocomplete is a result prompt, Autocomplete class. * @ options {* the location String Map for | | Point set to return to the scope of the result. For example, Types Array<String> Indicates the returned data type. Two Settings, the first is the default (that is, the set value is null) and will return all data. If the map is initialized to Beijing, input "small" in the input box, the input box will contain "small" keywords of a variety of types (such as catering, place names, etc.) prompt entry. The second setting is"city", will return the province, city, county, township street address type data. If the map is initialized to Beijing, input "small" in the input box, the input box will appear "Little Gold County" location name class prompt entry onSearchComplete Function after input characters in the input box, initiate list retrieval, after the completion of the callback Function. Parameters: AutocompleteResult input String | HTMLElement text input box element or the id * * *} / this. Autocomplete =function(options) {
		returnnew BMap.Autocomplete(options); } /** * for location, peripheral, and range retrieval. * @ the location Map for {| Point | String} * @ opts {* renderOptions LocalRenderOptions results set onMarkersSet Function Annotate the added callback function. Parameter: POis: Array, corresponding annotation can be obtained by marker attribute onInfoHtmlSet Function Callback Function after annotation bubble content is created. Parameter: POi: LocalResultPoi, the current annotation can be obtained through its marker attribute. HTML: HTMLElement onResultsHtmlSet Function Callback Function after the result list is added. Parameters: the container: HTMLElement, the HTML element used in the result list pageCapacity Number Set the capacity of each page. The value ranges from 1 to 100. For multi-keyword search, the capacity represents the Number of each keyword. 2-200 onSearchComplete Function The callback Function after the retrieval is complete. In the case of a multi-keyword search, the callback argument returns an Array of localResults in the same order as in the multi-keyword search *} * */ this.localsearch =function(location, opts) {
		returnnew BMap.LocalSearch(location, opts); } /** * create an instance of the address resolver ** */ this.geocoder =function() {
		returnnew BMap.Geocoder(); } /** ** Create Geolocation object instance ** */ this.Geolocation =function() {
		returnnew BMap.Geolocation(); } /** * This class represents a window containing information on the map. * * @ content {string | HTMLElement} to create a dashboard instance, among them the content support HTML content. Since version 1.2, the content parameter supports passing in DOM nodes * @opts {width Number Window width, in pixels. Value range: 0, 220-730. If you specify a width of 0, the width of the info window automatically adjusts the height Number of the info window in pixels based on its contents. Value range: 0, 60-650. If you specify a height of 0, the height of the information window is automatically adjusted according to its contents maxWidth Number The maximum width of the information window, in pixels. Value range: 220-730 Offset Size Indicates the offset of the information window position. By default, the bottom corner of an information window opened on a map points to its geographic coordinates. The bottom corner of an information window opened on a annotation depends on the infoWindowOffset property value of the icon used for the annotation. You can add an offset to the information window to change the default position. Support HTML contentenableAutoPan Boolean Whether to enable automatic map movement when info window opens (default enabled)enableCloseOnClick Boolean Enable Click on the map to close the info window (default enabled)enableMessage Boolean Specifies whether to display the SEND SMS button in the Message window (enabled by default). Message String Specifies the content of customized SMS messages. This option is optional. The complete SMS content includes: user-defined part + location link. If this parameter is not set, the default SMS content is displayed. The maximum length of a message is 140 characters} * */ this.infowindow =function(content, opts) {
		returnNew map.infoWindow (content, opts)} /** * Creates a text annotation instance. The point parameter specifies the location of the text annotation * @content {String} Title content * @opts {* offset Size Specifies the offset value of the text annotation position Point Specifies the location of the text annotationenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue

	 * }
	 * */
	this.Label = function(content, opts) {
		returnnew BMap.Label(content, opts); } /** * opens the Window window * @InfoWindow instantiated infoWindow window * @point {point coordinates point} creates a geographic point coordinate with the specified longitude and latitude ** / this.openInfoWindow =function(infoWindow, point) { this.pulic.openInfoWindow(infoWindow, point); }},function() {
	'use strict'; // Amap related method encapsulationif(! AMap) { console.error('Please check whether the config item and the js loaded map are correct! ');
		return; } / / var _toString = validation data type Object. The prototype. ToString; /** * Create the Map instance in the specified container, after which you need to call the map.centerandZoom () method to initialize the Map. Initialized not map will not be able to do anything * @ container {String | HTMLElement} * @ opt {provide the parameters of the * * * / / baidu attribute types describe minZoom Number display map permits the minimum level MaxZoom Number Maximum level mapType mapType of a map. The default value is BMAP_NORMAL_MAPenableHighResolution Boolean Specifies whether to enable the use of high-resolution maps. On iPhone4 and later devices, you can enable this option to obtain a higher resolution base image. This option is disabled by default for v1.2 and v1.3, and enabled for v1.4enableAutoResize Boolean Specifies whether to automatically adapt to map container changes. Enabled by defaultenableMapClick Boolean Specifies whether to enable the base map clickable function, enabled by default. Center point of the map You are advised to use zoom and Center properties to specify the level and center point of the map (added since V1.3) layers Array Array of map layers. The Array can be one or more layers. By default, it is a two-dimensional map. When multiple layers are superimposed, a common 2D map needs to instantiate a TileLayer class (added since V1.3) to realize the zoom level displayed on the map. If center and Level are not assigned, the default zoom value of the 3D map under the user's city is displayed by default. It can be set to a floating point number. (In V1.3.0, the level parameter is changed to Zoom, and the 3D map modification takes effect since V1.4.0) Center LngLat map center coordinate value labelzIndex Number Map annotation display sequence, Greater than 110 will display the default label on the base map over the overlay (circle, fold, plane). Zooms Array displays the zoom level on a PC. The default zoom level is [3,18] and the value ranges from [3-18]. On mobile devices, the default value is [3,19]. Value range is [3-19] lang String Map Language Type Optional values: zh_CN: Chinese simplified, EN: English, zh_en: Chinese bilingual. The default value is: Note: POI of Chinese, English, and Chinese maps may be inconsistent (added since V1.3) defaultCursor String Default mouse style of map. The parameter defaultCursor must comply with the CURSOR property specification of the CSS CRS String Reference coordinate system displayed on the map.'EPSG3857''EPSG3395''EPSG4326'AnimateEnable Boolean Specifies whether to use animations during map panning (e.g., calling panBy, panTo,setCenter,setZoomAndCenter and other functions will pan the map, whether to use animation pan effect), default istrueIsHotspot Boolean whether to enable map hotspot using animation, defaultfalseDo not open defaultLayer TileLayer (added since V1.3) the layer displayed by default in the current map. The default layer can be tilelayer. Satellite or a slice layer customized by TileLayer (deprecated since V1.3) rotateEnable Boolean Specifies whether the map is rotatable by defaultfalse. The default value for 3D view istrue, 2D view defaultfalse. ResizeEnable Boolean Specifies whether to monitor map container size changes. The default value isfalseShowIndoorMap Boolean Specifies whether to automatically display indoor maps with a vector base. Default on PCtrue, the mobile terminal default isfalseExpandZoomRange Boolean Specifies whether to extend the maximum zoom level. Use this Boolean in conjunction with the zooms propertytrueDragEnable Boolean Specifies whether the map can be moved by mouse drag and drop. The default istrue. This property can besetThe Status/getStatus methods control whether the zoomEnable Boolean map is zoomable. The default istrue. This property can besetThe Status/getStatus method controls whether the doubleClickZoom Boolean map can be enlarged by double-clicking the mouse. The default value istrue. This property can besetThe Status/getStatus methods control keyboardEnable Boolean specifies whether the map can be controlled by the keyboard. The default istrueDirectional keys control map translation,"+"and"-"Can control the map zoom, Ctrl+ "→" clockwise rotation, Ctrl+ "←" counterclockwise rotation. This property can besetThe Status/getStatus methods control whether the jogEnable Boolean map uses the easing effect. The default istrue. This property can besetThe Status/getStatus methods control scrollWheel Boolean whether the map can be zoomed with the mouse wheel. The default istrue. This property can besetThe Status/getStatus method controls whether the touchZoom Boolean map can be browsed by multi-touch zooming on the mobile terminal. The default istrue. To turn off the gesture zoom map, set tofalse. TouchZoomCenter Number can be default, when touchZoomCenter=1, the mobile end of the double finger zoom center to the center of the map, otherwise the default double finger center as the center mapStyle String set the map display style, currently support two kinds of map styles: The first: custom map style, such as"amap://styles/d6bf8c1d69cea9f5c696185ad4ac4c86"Can go to the map custom platform to customize their own personalized map style; Second: official style templates, such as"amap://styles/grey". See the development guide for additional template styles and custom map usage instructions. Features Array sets the support for the types of elements displayed on the map'bg'(Map background),'point'(POI point),'road'(roads),'building'ShowBuildingBlock Boolean Sets map to display 3D block effect, mobile also available. Recommended. ViewMode String Default is' 2D ', optional '3D', select '3D' to display 3D map effect. Pitch Number pitch Angle, default: 0, [0,83], invalid on 2D maps. PitchEnable Boolean Specifies whether pitching Angle can be set. In 3D view, it istrue, invalid in 2D view. BuildingAnimation Boolean Specifies whether the animation process is displayed when blocks appear and disappear. The 3D view is valid, default on PCtrueBy default on the mobile phonefalse. (supported since V1.4.0) skyColor String adjusts the skyColor with custom map, 3D view effective, such as'# ff0000 ". (Supported since V1.4.0)This class represents optional arguments to the Map constructor. It has no constructor, but can be represented as an object literal. * */ this.Map =function(container, opt) { var that = this.pulic = new AMap.Map(container, opt); // Trigger the instance method to override this.setpulic(1);returnthat; }; /** * create makeroverlay * @point {point coordinates} create a geographic point coordinates with the specified latitude and longitude * @opts {* // baidu parameter * offset Size annotation position offset value icon icon used for annotation objectenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
		enableDragging Boolean Whether drag is enabled, default isfalse
		enable4. Send Boolean Whether to respond to click events. The default istrueRaiseOnDrag Boolean Whether the annotation is enabled to leave the map surface effect when dragging and dropping the annotation. The default isfalseDraggingCursor String Style of the mouse pointer when dragging a cursor. Rotation Number Rotation Angle Shadow Icon Shadow Icon Title String Display content when the mouse moves to the marker // High Parameter map Map map object to display this marker Position LngLat Indicates the position displayed on the map. The default position is offset Pixel at the center of the map. The default value is Pixel(-10,-34). After the position is specified by Marker, the position at the upper left corner of the Marker is taken as the reference point by default to align with the given position. If the specified position of the Marker is aligned at position, a certain offset shall be set according to the size of the Marker. Icon String/ icon Icon to be displayed in dot marks. It can be a local Icon address or an Icon object. This property is invalid when there is valid content. Content String/Object dot marks the content to be displayed, which can be an HTML element String or an HTML DOM Object. The icon property will be overridden when content is valid. TopWhenClick Boolean Specifies whether marker is at the top when the mouse is clicked, defaultfalseBubble Boolean Whether to bubble events such as the mouse or touch of the overlay onto the map (added since v1.3) Default:falseDraggable Boolean Sets whether point markers can be dragged and moved. Default isfalseRaiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag Boolean raiseOnDrag String Cursor String Opera does not support custom CURSOR Visible Boolean to indicate whether the cursor is visible. The default istrueZIndex Number Indicates the sequence in which dot markers are added. ZIndex: 100 Angle Number Indicates the rotation Angle of a point mark. It is widely used to change the direction of vehicles. The Angle attribute is implemented using CSS3 and supports IE9 and later autoRotation Boolean whether it automatically rotates. If the path direction changes when using moveAlong animation, the dot mark automatically adjusts the Angle. The default isfalse. Widely used to automatically adjust the direction of the vehicle. Animation String Indicates the animation effect of dot marks. Default: "AMAP_ANIMATION_NONE" Optional: "AMAP_ANIMATION_NONE", no animation effect "AMAP_ANIMATION_DROP", label drop effect "AMAP_ANIMATION_BOUNCE", label bounce effect shadow Icon Mark shadow, Clickable Boolean Whether the Marker is clickable shape MarkerShape Sets the clickable region of Marker, ExtData Any User-defined attribute, support JavaScript API Any data type, such as id of Marker. Label {content,offset} add text annotation. Content is the content marked in the text, offset is the offset, and the upper left corner is the offset (0,0) *} * */ this.marker =function(point, opts) {
		opts = opts || {};
		//opts.map=this.pulic;
		opts.position = point;
		AMap.Marker.prototype.addEventListener = AMap.Marker.prototype.on;
		returnnew AMap.Marker(opts); } /** * // Baidu parameters * @url {String} URL address * @size {size} size * @opts {* Anchor Size Icon location anchor. This point is used to determine the location of the icon. It is the offset from the upper left corner of the icon, which by default is equal to the middle of the icon width and height. ImageOffset Size Specifies the offset of the image from the viewable area. When the information window is opened, the position of the sharp corner at the bottom of the information window relative to the upper left corner of the icon is equal to the anchor of the icon by defaultprintImageUrl String is used to print images, this property only applies to IE6, to solve the problem of IE6 printing style incorrect with filter *} * * // Gaard parameter * size size icon size, Default value (36,36) imageOffset Pixel specifies the imageOffset. When a large image is specified in image, size and imageOffset can be used to display the image address of the icon in the specified range image String. The default value is blue thumbpin image imageSize Size specifies the imageSize of an icon. Stretch or compress the image according to the preset Size. This value is the same as background-size in the CSS. Can be used to achieve hd effect on HD screen * */ this.icon =function(url, size, opts) {
		opts = opts || {};
		url ? opts.image = url : "";
		opts.size = size;
		returnnew AMap.Icon(opts); } /** * create a rectangular area Size object with the specified width and height * @width {Number} horizontal * @height {Number} vertical ** / this.size =function(width, height) {
		returnnew AMap.Size(width, height); } @lng {Number} latitude ** @lat {Number} latitude ** / this.point =function(lng, lat) {
		returnnew AMap.LngLat(lng, lat); } /** * create an instance of the address resolver ** / this.geocoder =function() {
		if(! AMap.Geocoder) { console.error('To use the AmAP Geocoder, you need to load plug-in support');
			return;
		}
		return new AMap.Geocoder({ lang: 'zh_cn'})} / * * * @ content {string | HTMLElement} to create a dashboard instance, among them the content support HTML content. Since version 1.2, the Content parameter supports passing in DOM nodes * @opts {isCustom Boolean whether to customize the form. Set totrue, the information window external box and content are added according to the value set by content (default isfalseAutoMove Boolean Specifies whether to automatically adjust the form to view (use this attribute to set whether to automatically pan the map when the information form is out of view, CloseWhenClickMap Boolean Controls whether to close the info form after mouse clicking on the map, defaultfalseContent String/HTMLElement Displays the content, which can be an HTML element String or an HTMLElement object. Custom form Example Size Size Information Form size (isCustom istrueOffset Specifies the offset of Pixel relative to the base point. The default value is the offset between BOTTOM_CENTER and base point. Position LngLat Information The base point at which the form is displayed (added since V1.2). ShowShadow Boolean Boolean Specifies whether to display information. The valuesfalseDoes not display form shadowtrueDisplay form shadow default value:false
	 }
	 * */
	this.InfoWindow = function(content, opts) {
		opts = opts || {};
		opts.content = content;
		opts.isCustom = false;
		opts.size = this.Size(opts.width, opts.height);
		opts.showShadow = false;
		returnNew amap.infoWindow (opts)} /** * creates a geographic point coordinate with the specified longitude and latitude ** / using the InfoWindow window window instantiated by @infoWindow * @point {point coordinate point} this.openInfoWindow =function(infoWindow, point) { infoWindow.open(this.pulic, point); } /** * Create a circle cover * @center {Point} center * @radius {Number} radius meter * @opts {* / String Circle fill color. StrokeWeight Number Specifies the width of the circular border, in pixels. StrokeOpacity Number specifies the opacity of the circular border. The value range is 0-1 fillOpacity Number Specifies the opacity of the circular padding. Value range: 0-1 strokeStyle String Indicates the pattern of the circle edge, which can be solid or consistentenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
			enableEditing Boolean Whether line Editing is enabled. Default isfalse
			enable1, Send Boolean Whether to respond to click events. DefaulttrueDefault zIndex:10 Center LngLat Center position bubble Boolean Whether to bubble events such as mouse or touch of overlay onto the map (added since V1.3) default:falseCursor String Specifies the cursor style when the mouse is hovering. Use custom cursor. IE supports only cur/ ANI/ICO formats. Unit: meter strokeColor String Line color, assigned using hexadecimal color code. The default value is# 006600The value range is [0,1], where 0 indicates full transparency and 1 indicates opacity. The default value is 0.9 strokeWeight Number Outline width fillColor String Indicates the filling color of the circle. The value is assigned using a hexadecimal color code. The default value is# 006600FillOpacity Float Circular fill transparency. The value ranges from 0 to 1, where 0 indicates full transparency and 1 indicates opacity. The default value is 0.9. StrokeStyle String Outline style, solid line :solid line :dashed line :dashed line: consistent extData Any User-defined attribute, support JavaScript API arbitrary data type, For example, the strokeDasharray Array, such as the id of Circle, is the dashed line and gap style of the outline of the shape. This attribute is valid when strokeStyle is consistent, and this attribute is valid in ie9+ : solid line: [0,0,0] dashed line: [10,10], [10,10] represents a dotted line consisting of a solid line of 10 pixels and a blank line of 10 pixels (and so on) : [10,2,10], [10,2,10] represents 10 pixels of solid line and 2 pixels of white space + 10 pixels of solid line and 10 pixels of white space (and so on) dotted line *} * */ this.circle =function(center, radius, opts) {
		opts = opts || {};
		opts.center = center;
		opts.radius = radius;
		returnnew AMap.Circle(opts); } @points {Array<Point>} * @opts { StrokeOpacity Number Specifies the transparency of the curve, in pixels. The value ranges from 0 to 1. StrokeStyle String Specifies the pattern of the curve, which is solid or consistentenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue
		enableEditing Boolean Whether line Editing is enabled. Default isfalse
		enable1, Send Boolean Whether to respond to click events. DefaulttrueThe ICONS Array<IconSequence> sets the ICONS that fit the polyline // Map map displays the stacking order of the polyline coverings of the map object zIndex Number. The default stacking order is first added at the bottom layer and then added at the top layer. ZIndex: 50 bubble Boolean Whether to bubble overlay events such as mouse or touch on the map (added since V1.3) Default: zIndex: 50 bubble BooleanfalseCursor String Specifies the cursor style used when the cursor is hovering. Custom CURSOR. IE supports only cur/ ANI/ICO formats. Opera does not support custom cursorfalseIsOutline Boolean Whether a line has a stroke, defaultfalseBorderWeight Number Specifies the width of the stroke. Default is 1trueDefault:# 000000StrokeColor String Line color, assigned using a hexadecimal color code. The default value is# 006600StrokeOpacity Number Specifies the line transparency. The value ranges from 0 to 1, where 0 indicates full transparency and 1 indicates opacity. Default: 0.9 strokeWeight Number Line width, unit: StrokeDasharray Array indicates the dashed line and gap pattern of the outline of the strokeDasharray Array. This attribute is valid when strokeStyle is consistent. This property is valid in ie9+ : solid line: [0,0,0] dashed line: [10,10], [10,10] represents a dotted line consisting of 10 pixels of solid line and 10 pixels of blank (and so on) : [10,2,10], [10,2,10] represents a dotted line consisting of 10 pixels of solid line and 2 pixels of white space + 10 pixels of solid line and 10 pixels of white space (and so on)'miter'Sharp Angle, other optional values:'round'Rounded corners,'bevel'LineCap String Style for drawing caps at both ends of a broken line. The default value is'butt'Headless, other optional values:'round'Round head,'square'Square header dragGable Boolean Sets whether polylines can be dragged and moved. Default isfalseExtData Any User-defined attribute that supports JavaScript API Any data type, such as the ID of Polyline. ShowDir Boolean Specifies whether to display white directional arrows in the extended path. Defaultfalse. Canvas is valid for drawing. It is recommended to use Canvas when the width of broken line is greater than 6. Direction arrows are not supported in 3D view (changed from V1.4.0) *} * */ this.polyline =function(points, opts) {
		opts = opts || {};
		if(_toString.call(points) === "[object Array]") {
			for(var i = 0; i < points.length; i++) {

				if(_toString.call(points[i]) === "[object Object]") { points[i] = [points[i].lng, points[i].lat]; }}}if(_toString.call(points) === "[object Object]") {
			var ns = [points.lng, points.lat];
			points = ns;
		}
		if(ns) {
			opts.path = [points];
		} else {
			opts.path = points;
		}

		//opts.map=this.pulic;
		returnnew AMap.Polyline(opts); } /** * create a text annotation instance. The point parameter specifies the location of the text annotation * @content {String} Title content * @opts {// Baidu parameter * offset Size Specifies the offset value of the text annotation position Point Specifies the location of the text annotationenableMassClear Boolean is calling map.clearOverlays to clear this covering. Defaulttrue} * */ this.Label =function(content, opts) {
		opts = opts || {};
		//opts.map=this.pulic;
		opts.text = content;
		returnnew AMap.Text(opts); } /** * constructs a pixel coordinate object. * @x{Number} set x direction Pixel coordinates * @y{Number} set y direction Pixel coordinates * */ this.Pixel =function(x, y) {
		returnnew AMap.Pixel(x, y); } /** * intelligent search * @map {map} * @obts {* input {string} input * output {string/HTMLDivElement} output set callback Function Callback to search results *} * */ this.localSearch =function(map, opts) { opts = opts || {}; var that = opts; // Create intelligent fillif(! AMap.Autocomplete) { console.error('Using Amap LocalSearch requires plug-in support');
			return; } var auto = new AMap.Autocomplete({ input: opts.input, output: opts.output }); var placeSearch = new AMap.PlaceSearch({ map: map }); // Construct the location query class amap.event. AddListener (auto,"select".function(e) {
			if(that && that.callback) { that.callback(e); }}); / / register to monitor, elected in a record triggered when} / * * * * * * * a Rectangle area search/enclosing SearchInRectangle =function(d) {var map = this.pulic, // rectangle = null, // rectangle = null; // area search /** * untying events ** /!function removeListener() {
            map.off('mousedown', mousedownfn);
            map.off('mousemove', mousemovefn);
            map.off('mouseup', mouseupfn);
            document.removeEventListener('mouseup', mouseupfn,false); } (); /** * Mouse press down the event function ** /functionMousedownfn (e) {// Set mousedownfn(e) {map.setStatus({dragEnable:false //trueCan drag}); southWest = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat); //console.log('the mouse mousedown',e.lnglat.lng+'| |'+e.lnglat.lat );
			rectangle = new AMap.Rectangle({
				map: map,
				bounds: new AMap.Bounds(southWest, southWest),
				strokeColor: d.strokeColor || "#1791fc"StrokeOpacity: d.s trokeOpacity | | 0.8, strokeWeight: d.s trokeWeight | | 2, fillColor: d.f illColor | |"#1791fc"FillOpacity: d.f illOpacity | | 0.35, dragEnable:! 1, strokeStyle: d.strokeStyle ||"solid", strokeDasharray: d.strokeDasharray || [10, 5], zIndex: d.zIndex || 10, bubble: ! 0, cursor:'pointer'}); // console.log(southWest.rectZoomIn,'southWest'); } // Bind the mouse movement event map.on('mousemove', mousemovefn); /** * Mouse movement event function ** /function mousemovefn(e) {
			//console.log(southWest);
			if(southWest) {
				//console.log('the mouse mousemove',e.lnglat.lng+'| |'+e.lnglat.lat ); var northEast = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat); Var Bounds = new AMap.Bounds(southWest, northEast); Rectangle && rectangle. SetBounds (Bounds);if(mouseupfn.isclear) { mouseupfn.isclear = 0; } } // console.log(map.getBounds()); } // Bind the mouse bounce event to map.on('mouseup', mouseupfn); /** * mouse click event function ** /function mouseupfn(e) {
			if(mouseupfn.isclear) {
				return false; } mouseupfn.isclear = 1; // Set map.setStatus({dragEnable:true //trueCan drag}); // Remove the overlaysetTimeout(function() {
				if(rectangle) { map.remove(rectangle); rectangle = null; }}, 200); southWest = null; // Perform the callbackif(d.callback) d.callback(rectangle.getBounds());
			//console.log('the mouse mouseup',e.lnglat.lng+'| |'+e.lnglat.lat ); } // Bind the mouse press event map.on('mousedown', mousedownfn); / / to the document binding mouseup event document. The addEventListener ('mouseup', mouseupfn, false); * * * *} / coordinate transformation baidu to Scott * @ lnglat {lnglat | Array. < lnglat >} latitude and longitude * @type{String} GPS :GPS original coordinates; Baidu latitude and longitude; Mapbar: latitude and longitude; * */ this.convertFrom =function(lnglat, callback) {

		AMap.convertFrom(lnglat, "baidu", callback)

	}

}]);
Copy the code

The above code basically achieves our requirements recently, but the code performance needs to be optimized, such as instance point and instance circle, which can be cached. Such as:

// Cache var d=function(){ var cache={ }; // Cache listfunction sum(){
		var arg=[].slice.call(arguments);
		args=arg.join(),
		l=arguments.length;
		if(cache[args]){
			return cache[args];
		}
		var n=0;
		while(--l){
			n+=arguments[l];
		}
		console.log('----------- only counts the first time -------')
		cache[args]=n;
		return n;
	}
	return {
		sum:sum,
	}
}();
Copy the code

Use closure features to cache data for faster feedback to users.

<div id="Map" style="height:500px;">
			
</div>
Copy the code

js

Gis_map. config = {mapType: 1, //0: baidu map, 1: Gaode map, 2: Tencent map} var maps = null; // Execute main function. Gis_Map.init(); maps = Gis_Map.Map('Map', { enableMapClick: false, minZoom: 5, });
//console.log(Gis_Map.pulic.centerAndZoom,'Gis_Map.pulic.centerAndZoom'); Var point = gis_map.point (116.404, 39.915); CenterAndZoom (point, 5); / / whether to enable the zoom setting maps. EnableScrollWheelZoom (true); //console.log(maps); /** */ maps.adDeventListener ('click'.function(e) { }); Var ICONS = gis_map.icon ('js/map_js/icon.png', Gis_Map.Size(48, 53)); Maker var maker = gis_map. Marker(gis_map. Point(112.361031, 36.391437), {title:'maker', icon: icons }); Gis_Map. ConvertFrom (Gis_Map. Point (114.469026, 35.45613),function(a, b) {
	console.log(a, b);
	if(b.info === 'ok') {

		var maker_1 = Gis_Map.Marker(Gis_Map.Point(b.locations[0].lng, b.locations[0].lat), { title: 'maker_1', icon: icons }); maps.addOverlay(maker_1); }}); maker.addEventListener('click'.function(e) {
	var p = e.target;
	var point = Gis_Map.Point(p.getPosition().lng, p.getPosition().lat);

	var winfor = Gis_Map.InfoWindow('
      
InfoWindow longitude: '
+ p.getPosition().lng + 'Current latitude:' + p.getPosition().lat + '
'
, { width: 400, height: 200 }); Gis_Map.openInfoWindow(winfor, point); }); // Add maps.addOverlay(maker); Var yuan = gis_map. Point(116.404, 39.915), 200000, {fillColor:"blue", // fill color strokeWeight: 1, // stroke thickness fillOpacity: 0.3, // fillOpacity: 0.3 // stroke transparency}); maps.addOverlay(yuan); Var p1 = [116.148568, 37.904113]; Var p2 = [116.167794, 37.934447]; Var p3 = [116.230965, 37.960437]; Var p4 = [116.277657, 37.990748]; Var p5 = [116.373788, 38.014555]; var xian = Gis_Map.Polyline([p1, p2, p3, p4, p5], { strokeColor:"# 000000", // Set color strokeWeight: 10, // width strokeOpacity: 1, // transparency:"solid" }); // console.log(xian); maps.addOverlay(xian); var label = Gis_Map.Label('Test data', {offset: gis_map. Pixel(2, 5), position: [112.361031, 36.391437],}); maps.addOverlay(label); var text = new AMap.Text({ text:'Plain text tag', textAlign: 'center', / /'left' 'right'.'center', verticalAlign: 'middle'//middle, bottom draggable:true, cursor: 'pointer', angle: 10, style: { 'background-color': 'yellow'.'border': 'solid 1px #0088ff'.'padding': '10px 20px'}, position: [116.396923, 39.918203]}); Gis_map. LocalSearch(maps, {input:'search', output: 'list', callback: function(e) { console.log(e); }}); Var point1 = gis_map. Point(116.368904, 39.923423); Var point2 = gis_map. Point(116.387271, 39.922501); console.log(maps.getDistance(point1, point2),'===== The distance between two points'); /** * Return the rectangle coordinate position * parameter * map map to display the stacked order of the rectangle object zIndex Number default zIndex:10 bounds Bounds bubble Boolean whether to bubble events such as mouse or touch of overlay onto the map default:falseCursor String Specifies the cursor style when the mouse is over. Use custom cursor. IE only supports curCUR/ANI/ICO format. The default value is# 006600The value range is [0,1], where 0 indicates full transparency and 1 indicates opacity. The default value is 0.9 strokeWeight Number Outline width fillColor String Specifies the filling color of the rectangle. The value is assigned using a hexadecimal color code. The default value is# 006600FillOpacity Float Rectangle fill transparency. The value ranges from 0 to 1, where 0 indicates full transparency and 1 indicates opacity. The default value is 0.9. StrokeStyle String Outline style, solid line :solid line :dashed line :dashed line: consistent extData Any User-defined attribute, support JavaScript API arbitrary data type, For example, the id of Rectangle and other strokeDasharray Array are dashed lines and gaps in the outline of the shape. This attribute is valid when strokeStyle is consistent. This attribute is valid in ie9+ browser: solid line: [0,0,0] dashed line: [10,10], [10,10] represents a dotted line consisting of a solid line of 10 pixels and a blank line of 10 pixels (and so on) : [10,2,10], [10,2] represents a dotted line composed of 10 pixels of solid line and 2 pixels of white space + 10 pixels of solid line and 10 pixels of white space (and so on) * * */ Gis_Map.function(e) {// Rectangle's Bounds [scope] console.log()'SearchInRectangle=====callback', e); }});Copy the code

conclusion

Sometimes change the wheel or make the wheel! You’re only successful if you can handle them. Through the above code writing, let oneself go a step on the architecture. Only by constantly learning and trying, can you realize your career plan.