First, use scenarios
Maps can be used in a wide range of scenarios. Map positioning can more intuitively explain the location and surrounding environment, so that users can better understand the geographical location information, navigation function better path planning, to facilitate travel. Location, navigation and so on have become one of the most common functions on the Internet.
Two, technical introduction
There are many common map apis in the market, such as:
Baidu Map API: lbsyun.baidu.com
Amap AP: lbs.amap.com
Tencent map API:lbs.qq.com
Sogou Map API: map.sogou.com/api/
The most commonly used are amap API(Ali) and Baidu Map API.
What I want to talk about here is baidu map API.
3. Use of technology
The introduction is: positioning technology, mainly about path planning and navigation.
1 Account Description
Check the API address: lbsyun.baidu.com
To use the service, you need to register an account and apply for a key (AK). There is no limit on the number of times the interface can be used
- Log in
- Access the console
- View application > Create Application, enter the application name and application type, select all services, and set the whitelist to * during development
- submit
You can get the AK for the service
2 helloworld
Prepare an HTML page and import a JS file in the format of
<script type="text/javascript" src="Https://api.map.baidu.com/api?v=1.0&type=webgl&ak= your key">
Copy the code
Then create a map container.
<! DOCTYPEhtml>
<html>
<head>
<meta name="viewport" content="Initial - scale = 1.0, the user - the scalable = no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello, World</title>
<style type="text/css">
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#container{height:100%}
</style>
<script type="text/javascript" src="Https://api.map.baidu.com/api?v=1.0&type=webgl&ak= your key">
</script>
</head>
<body>
<div id="container"></div>
<script type="text/javascript">
var map = new BMapGL.Map("container");
// Create a map instance
var point = new BMapGL.Point(116.404.39.915);
// Create the point coordinates, denoted by tiananmen coordinates
map.centerAndZoom(point, 15);
// Initialize the map, set the center point coordinates and map level
</script>
</body>
</html>
Copy the code
Then create a map object in JS, place it in the container, and then you can also set a mark point, with the mark point as the center, expand the map.
Note that the API is related to the version of js introduced, changing the JS path to someone else’s Baidu map may cause the invalidation of the customized map [because of different API versions], for example, the map API of Web development is BMapGL.
Part OF API
Website: mapopen-pub-jsapi.bj.bcebos.com/jsapi/refer…
Map
This class is the core class of the Map API and is used to instantiate a map. Note that the namespace of the Map API for the WebGL version is BMapGL, which varies from version to version. Example: const map = new bmapgl.map (‘container’);
The constructor | describe |
---|---|
Map(container: String | HTMLElement, opts: MapOptions ) | Create a Map instance in the specified container, and then initialize the Map by calling the map.centerandZoom () method. ** Uninitialized maps will not be able to perform any operations |
It is recommended to place the map initialization at the top of the JS, and then put some operations, such as label retrieval and relocation, in the initialization function.
This way, when our center point needs to be retrieved from the database, or when we need to obtain user location, we can call map.centerandZoom () to initialize the Map, passing in a fixed default point.
Otherwise the experience will be poor if the query fails or the user refuses to give a location, the map can’t be initialized or initialization takes too long.
methods | The return value | describe |
---|---|---|
enableDragging() | none | Enable map drag, enabled by default |
disableDragging() | none | Disable map drag and drop |
enableInertialDragging() | none | Enable map inertial drag, disabled by default |
disableInertialDragging() | none | Disable map inertial drag |
enableScrollWheelZoom() | none | Allows maps to be zoomed by mouse wheel, disabled by default |
disableScrollWheelZoom() | none | Disables map zooming by mouse wheel |
enableContinuousZoom() | none | Enable double click smooth zoom effect |
disableContinuousZoom() | none | Turn off the double click smooth zoom effect |
enableResizeOnCenter() | none | The center point of open map resize remains unchanged |
disableResizeOnCenter() | none | Resize center point of closed map remains unchanged |
enableDoubleClickZoom() | none | Enable map double – click zoom, left – click zoom, right – click zoom |
disableDoubleClickZoom() | none | Cancel the map double-click zoom |
enableKeyboard() | none | Enable keyboard operations. By default, keyboard operations are disabled. The top, bottom, left and right keys of the keyboard can move the map continuously. Pressing two of these keys simultaneously moves the map diagonally. The PgUp, PgDn, Home, and End keys shift the map by 1/2 of its size. The + and – keys make the map zoom in or out one level |
disableKeyboard() | none | Disabling keyboard operations |
enablePinchToZoom() | none | Enable two-finger zoom map. |
disablePinchToZoom() | none | Disables two-finger zoom maps. |
enableRotateGestures() | none | Whether it is possible to rotate the map using gestures. |
enableTiltGestures() | none | Whether it is allowed to tilt the map with gestures. |
enableAutoResize() | none | Enable Automatic container size adaptation. This function is enabled by default |
disableAutoResize() | none | Disable auto adaptation to container size changes |
checkResize() | none | This method is called to relay the map after the map container changes |
resize() | none | Forces the map to be resized, at which point the image data required for the view is recalculated and redrawn against the current container size. When auto View is turned off (enableAutoResize Config), you need to call this method to force a map refresh. |
getSize() | Size | Returns the current size of the map, in pixels |
getContainerSize() | Size | Gets the map container size |
getZoomUnits() | Number | Returns the current map level and how many units of flat Mercator coordinates a pixel corresponds to |
getContainer() | HTMLElement | Returns the DOM container element of the map. Map containers are obtained by implementing the Control.initialize() method and adding the container elements of the Control to the map when creating user-defined controls |
pixelToPoint(pixel: Pixel ) | Point | Pixel coordinates are converted to latitude and longitude coordinates |
pointToPixel(point: Point ) | Pixel | Convert latitude and longitude coordinates to pixel coordinates |
lnglatToMercator(lng: Number, lat: Number) | [McLng, McLat] | Latitude and longitude sphere coordinates are converted to Mercator plane coordinates |
mercatorToLnglat(McLng: Number, lat: McLat) | [lng, lat] | Mercator plane coordinates are converted to latitude and longitude spherical coordinates |
isLoaded() | boolean | Returns whether the map was initialized by centerAndZoom |
addSpots(spots: Array, options: Object) | number | Add location areas as virtual clickable areas on the map. Parameter spots indicates the hot zone point group, and options is optional. Returns the area ID. |
getSpots(id: string) | Array | Returns an array of locations based on id |
removeSpots(id: number) | none | Removes array of regions by ID |
clearSpots() | none | Clears the site area, which clears all virtual pointable data |
clearLabels() | none | Clear all custom base map labels in the current map |
addLabelsToMapTile(labels:Array) | none | Add text to the base map, these text and the base map text will participate in dodge. |
removeLabelsFromMapTile(labelUids:Array) | none | Removes the text annotation from the base image, taking uid array as the parameter and removing it according to the UID in the array |
getIconByClickPosition(clickPosition: Pixel) | Object | null | Get the base map icon in the current point by clicking the coordinate, return {name, uid, position} if it is obtained, otherwise return null |
setBounds(bounds:Bounds) | none | Set dragable area of the map. Parameter is the range of dragable area of the map |
getBounds() | Bounds | Gets the rectangular region of the map’s current field of view, expressed in geographic coordinates. Returns an empty map if the map has not been initializedBounds Instance. |
getCoordType() | string | Gets the map coordinate type, CoordType constant |
getMapStyleId() | string | Gets the current map style ID, or the style name for the built-in style; For custom styles, the internally generated style ID is returned |
getPanes() | MapPanes | Gets the overlay container element that returns the map overlay container object |
getInfoWindow() | InfoWindow | null | Gets an instance of the currently open info window, or if the current map does not have an open status info windownull |
setDefaultCursor(cursor: String) | none | Sets the default mouse pointer style for the map. The parameter cursor must comply with the CSS cursor property specification |
getDefaultCursor() | String | Gets the default mouse pointer style of the map, returning a cursor value |
setDraggingCursor(cursor: String) | none | Sets the mouse pointer style for dragging and dropping a map. The parameter cursor must comply with the CSS cursor property specification |
getDraggingCursor() | String | Returns the mouse pointer style for dragging and dropping the map |
setMinZoom(zoom: Number) | none | Sets the minimum level allowed on the map. The value must be at least the minimum level allowed by the map type |
setMaxZoom(zoom: Number) | none | Sets the maximum level allowed on the map. The value cannot be greater than the maximum level allowed by the map type |
getDistance(start: Point , end: Point ) | Number | Returns the distance between two points in meters |
getMapType() | MapTypeId | Return map type |
setViewport(view: Array | Viewport , viewportOptions: ViewportOptions ) | none | Set the map view according to the geographic region or coordinates provided. The adjusted view is guaranteed to include the geographic region or coordinates provided |
getViewport(view: Array< Point >, viewportOptions: ViewportOptions ) | Viewport | The best map view is obtained according to the geographic region or coordinates provided. The returned object contains the Center and Zoom attributes, representing the center point and level of the map, respectively. This method only returns the view information and does not apply the new center point and level to the current map |
centerAndZoom(center: Point , zoom: Number) | none | Let’s initialize the map. If the center type is Point, zoom must be assigned levels 3-19. If the hd base map (developed for mobile terminals) is called, Zoom can be assigned levels 3-18. If the center type is a string, such as “Beijing”, zoom can be ignored, and the map will automatically match the best zoom level according to Center |
panTo(center: Point ) | none | Change the center point of the map to the given point, jump to the specified center point for rendering. If the point is already visible in the current map view, it is moved to the center point in a smooth animation. You can configure to force movement without animation |
panBy(x: Number, y: Number) | none | Move the map x pixels horizontally and y pixels vertically. If the specified pixel is larger than the viewable area or if no animation is specified in the configuration, the slide effect is not performed |
flyTo(center: Point , zoom: Number) | none | Fly to the specified center point and level, available for use on the positioning zoom map |
reset() | none | Reset the map to restore the center point and level of the map when it was initialized |
setCenter(center: Point | String[, options: Object]) | none | Set the center point of the map. In addition to being a coordinate point, center also supports city names. Optional configuration parameters include ‘noAnimation: Boolean ‘whether animation is disabled; This method is called after the ‘callback: function’ animation ends, or immediately if there is no animation |
getCenter() | Point | Returns the current center point of the map |
setMapType(mapTypeId: MapTypeId ) | none | Setting map Type |
setZoom(zoom: Number[,options]) | none | Switches the view to the specified zoom level, leaving the center point coordinates unchanged. Note: When an information window is open on the map, map zooming will keep the coordinate position of the information window unchanged. Optional configuration parameters include ‘noAnimation: Boolean ‘whether animation is disabled; This method is called after the ‘callback:function’ animation ends, or immediately if there is no animation; ‘zoomCenter: Point’ zooms to the center Point of the map by default |
getZoom() | Number | Returns the current zoom level of the map |
zoomIn() | none | Zoom in level 1 view |
zoomOut() | none | Zoom out level 1 view |
addControl(control: Control ) | none | To add a control to a map, a control instance can only be added to the map once |
removeControl(control: Control ) | none | Removes the control from the map. This removal has no effect if the control was never added to the map |
addContextMenu()(menu: ContextMenu ) | none | Add right-click menu |
removeContextMenu()(menu: ContextMenu ) | none | Remove right-click menu |
addOverlay(overlay: Overlay ) | none | To add a overlay to a map, an instance of a overlay can only be added to the map once |
removeOverlay(overlay: Overlay ) | none | Remove overlay from map. If the overlay was never added to the map, the removal has no effect |
clearOverlays() | none | Clear all overlay from the map |
pointToOverlayPixel(point: Point ) | Pixel | Get the coordinates of the corresponding coverings container based on geographic coordinates. This method is used to customize coverings |
overlayPixelToPoint(pixel: Pixel ) | Point | Obtain the corresponding geographic coordinates according to the coordinates of the covering container |
getOverlays() | Array< Overlay > | Gets all overlay objects on the current map, returning a collection of overlay objects |
getPanes() | MapPanes | Returns the list of map overlay containers |
getCurrentMaxTilt() | number | Gets the maximum tilt Angle allowed on the current map |
hightlightSpotByUid(uid: string, tilePosStr: string) | none | The POI on the base map is highlighted based on uid, where the parameter tilePosStr is the position string of label |
resetSpotStatus() | none | Reset hot spot status, to unhighlight hot spot |
addAreaSpot() | none | Reset hot spot status, to unhighlight hot spot |
getAreaSpot(id: string) | Array | Returns an array of locations |
removeAreaSpot(id: string) | none | Remove array of regions |
clearAreaSpots() | none | Clears the site area, which clears all virtual pointable data |
setTrafficOn() | none | Turn on the traffic layer |
setTrafficOff() | none | Close the road condition layer |
showOverlayContainer() | none | Display overlay |
hideOverlayContainer() | none | Cover is not shown |
setMapStyleV2(config: Object) | none | Set the personalization map to personalization configuration object |
startViewAnimation(viewAnimation: ViewAnimation) | Number | Start perspective animation |
cancelViewAnimation(viewAnimation: ViewAnimation) | none | Stop perspective animation |
getMapScreenshot() | url | Get map screenshots. Earth mode is not supported. PreserveDrawingBuffer: true is required to initialize the map, otherwise black screen is displayed |
loadMapStyleFiles(callback: Function) | none | The style file required to load the current style of the map, callback is the callback function after loading successfully |
setCopyrightOffset(logo: Object, cpy: Object) | none | Set the location of copyright information. Logo is the location of logo, and copyright is the location of text |
destroy() | none | Destroy the map. When rendering the map using WebGL, if you confirm that the map instance is no longer used, you need to call this method to destroy the WebGL context. Otherwise, frequent creation of new map instances will cause the browser to send a warning: too many WebGL Context |
isSupportEarth() | boolean | Check whether the browser supports earth, return true if it does, false otherwise |
The event | parameter | describe |
---|---|---|
click | {type, target, latlng, pixel, overlay} | This event is triggered when a map is left-clicked. When double-clicked, the sequence of events generated is: click click dblclick |
dblclick | {type, target, pixel, point} | This event is triggered when you double-click a map |
rightclick | {type, target, latlng, pixel, overlay} | This event is triggered when you right-click a map. When double-clicked, the resulting sequence of events is: rightclick rightclick rightdblclick |
rightdblclick | {type, target, latlng, pixel, overlay} | This event is triggered when you right-click a map |
maptypechange | {type, target} | This event is triggered when the map type changes |
mousemove | {type, target, latlng, pixel, overlay} | This event is triggered when the mouse moves over a map area |
mouseover | {type, target} | This event is triggered when the mouse moves over a map area |
mouseout | {type, target} | This event is triggered when the mouse moves out of the map area |
movestart | {type, target} | Trigger this event when map movement begins |
moving | {type, target} | Trigger this event while the map is moving |
moveend | {type, target} | Trigger this event when map movement ends |
zoomstart | {type, target} | This event is triggered when the map changes zoom level |
zoomend | {type, target} | This event is triggered when the map changes zoom level |
addoverlay | {type, target} | This event is emitted when a single overlay is added to a Map using the map.addoverlay () method |
addcontrol | {type, target} | This event is emitted when a single control is added to a Map using the map.addControl () method |
removecontrol | {type, target} | This event is emitted when a single control is removed using the map.removecontrol () method |
removeoverlay | {type, target} | This event is emitted when a single overlay is removed using the map.removeOverlay () method |
clearoverlays | {type, target} | This event is triggered when all coverings are removed at once using the map.clearoverlays () method |
dragstart | {type, target, pixel, point} | Triggered when you start dragging the map |
dragging | {type, target, pixel, point} | Triggered during map dragging |
dragend | {type, target, pixel, point} | Triggered when stopping dragging maps |
resize | {type, target, size} | This event is triggered when the size of the map’s viewable area changes |
Geolocation
If the user fails to return the current location of the user, the locating interface of the browser will be invoked first. If the user fails to return the current location of the user, the locating interface of the browser will be invoked. If the user refuses to authorize locating, no locating result will be returned.
The constructor | describe |
---|---|
Geolocation() | Create a Geolocation object instance |
methods | The return value | describe |
---|---|---|
getCurrentPosition(callback: Function, opts:PositionOptions) | none | Returns the current location of the user. When the location is complete (including success, failure, and timeout), the callback parameter is GeolocationResult. Otherwise, the callback parameter is NULL |
getStatus() | StatusCode | Status code after the location is complete. BMAP_STATUS_SUCCESS, BMAP_STATUS_UNKNOWN_LOCATION, BMAP_STATUS_PERMISSION_DENIED, and BMAP_STATUS_TIMEOUT |
enableSDKLocation() | none | Sdk-assisted locating takes effect only when mobile Web hybrid development is used and the SDK-assisted locating function is enabled |
disableSDKLocation() | none | Disable sdK-assisted location |
Marker
This class represents an image annotation on a map.
The constructor | describe |
---|---|
Marker(point: Point , opts: MarkerOptions ) | Create an image annotation instance. The point parameter specifies the geographic location of the image annotation |
methods | The return value | describe |
---|---|---|
setIcon(icon: Icon ) | none | Sets the icon object to use for the annotation |
getIcon() | Icon | Returns the icon object used for the annotation |
setPosition(position: Point ) | none | Sets the geographic coordinates of the annotation |
getPosition() | Point | Returns the geographic coordinates of the annotation |
setOffset(offset: Size ) | none | Sets the offset value of the annotation |
getOffset() | Size | Returns the offset value of the annotation |
setTitle(title: String) | none | Sets the annotation’s title, which is displayed when the mouse is over the annotation |
getTitle() | String | Returns the title of the annotation |
setLabel(label: Label ) | none | Add text annotations to annotations |
getLabel() | Label | Returns the text content of the annotation |
enableDragging() | none | Enable annotation drag and drop |
disableDragging() | none | Turn off annotation drag and drop |
enableMassClear() | none | Allows coverings to be cleared in the Map. ClearOverlays method |
disableMassClear() | none | Forbidden coverings to be cleared in the Map. ClearOverlays method |
setZIndex(zIndex: Number) | none | Set the zIndex of the overlay |
getMap() | Map | Returns the map object of the overlay |
setRotation(rotation: Number) | none | Sets the rotation Angle of the point |
getRotation() | Number | Gets the rotation Angle of a point |
addEventListener(event: String, handler: Function) | none | Add event listener functions |
removeEventListener(event: String, handler: Function) | none | Remove the event listener function |
Label
The constructor | describe |
---|---|
Label(content: String, opts: LabelOptions ) | Create a text annotation instance. The point parameter specifies the geographic location of the text annotation |
methods | The return value | describe |
---|---|---|
setStyle(styles: Object) | none | Sets the text annotation style that will be applied to the container elements of the text annotation. Styles are JavaScript object constants, such as setStyle({color: “red”, fontSize: “12px”}) note: if the CSS property name contains a hyphen, remove the hyphen and capitalize the following characters. For example, write the backgroundColor as backgroundColor |
setContent(content: String) | none | Sets the content of the text annotation. Supports HTML |
setPosition(position: Point) | none | Set text annotation coordinates. Only valid text annotations added through the map.addoverlay () method |
getPosition() | Point | Gets the geographic coordinates of the Label |
setOffset(offset: Size) | none | Sets the offset value of the text annotation |
getOffset() | Size | Returns the offset value of the text annotation |
setTitle(title: String) | none | Sets the title of the text annotation to be displayed when the mouse is over the annotation |
getTitle() | String | Returns the title of the text annotation |
enableMassClear() | none | Allows coverings to be cleared in the Map. ClearOverlays method |
disableMassClear() | none | Forbidden coverings to be cleared in the Map. ClearOverlays method |
setZIndex(zIndex: Number) | none | Set the zIndex of the overlay |
setPosition(position: Point) | none | Setting geographic Coordinates |
getMap() | Map | Returns the map object of the overlay |
addEventListener(event: String, handler: Function) | none | Add event listener functions |
removeEventListener(event: String, handler: Function) | none | Remove the event listener function |
The event | parameter | describe |
---|---|---|
click | event{type, target} | This event is triggered when a text annotation is clicked |
dblclick | event{type, target} | This event is triggered by double-clicking a text annotation |
mousedown | event{type, target} | This event is triggered when the mouse is pressed over a text annotation |
mouseup | event{type, target} | This event is triggered when the mouse is released over a text annotation |
mouseout | event{type, target} | This event is triggered when the mouse moves away from a text annotation |
mouseover | event{type, target} | This event is triggered when the mouse enters the text annotation area |
remove | event{type, target} | Triggered when removing text annotations |
rightclick | event{type, target} | Trigger this event when you right-click on a annotation |