1. Perform preliminary configuration of AMap JSAPI 1.4.15 document 2 according to the official autonavi tutorial. Follow the official sample center to create the sample center of the map

Next, first look at the renderings:

1. Initialize the map

After the map container is created, some default parameters need to be configured during initialization. Here are some commonly used parameters. Other effects can be added by referring to the API

Dom: Class GeoMap {constructor() {this.el ='map_container' This. defaultConfig = {// Default zoom configuration zoom: 16, // default zoom level touchZoomCenter: 1, // zoom to map center resizeEnable: True, // Monitor map container size changes doubleClickZoom: } this.map = null // map instance this.mapMove = false // Map is moving this.centerPixel = {y: '-999', x: '- 999} / / he some default location} / / initializes the map initFn () {enclosing createMap () / /... } createMap() {this.map = new amap.map (this.el, Enclosing defaultConfig) / / add your favorite style to map (background color). This map. The setMapStyle (' amap: / / styles / 28 d5c5df182464d14316bfa41383096c ')} / / . } export default new GeoMap()Copy the code

2. Map insertion point

First of all, draw a center point on the map. The effect needs to be achieved:

  1. Cannot move with a map drag
  2. In the center of the map container

Map box as the parent element, tie point for absolute positioning, to achieve the first point;

Dom: <div id='map_container'> // map container <div id='center_icon' style={{left: '${instance.centerpixel.x}px', top: Y}px '}}> <img SRC =' map_container '/> </div> </div> CSS: #map_container {flex: 1; position: relative; #center_icon { position: absolute; z-index: 101; >img{ width: 52px; height: 64px; / / -- -- -- -- -- -- -- - the following code below to do detailed introduction -- -- -- -- -- -- -- -- -- the position: relative; top: -64px; left: -26px; }}}Copy the code

Then you need to set the left and top values of the tie point. How to dynamically set the pixel values of the tie point? Here, we use The Autonavi API, getCenter() to obtain the latitude and longitude coordinates of the map center lngLatToContainer() and convert them into pixel coordinates of the map container

    setCenterIcon() {
        let lnglat = this.map.getCenter()
        let pixel = this.map.lngLatToContainer(lnglat)
        this.centerPixel = pixel
    }
Copy the code

The tie point picture needs relative positioning top:- its height left:- its width /2, the reason is: the anchor point is positioned from the top left corner of the box to the center (dotted box), so we need to move (dotted box) to the position (solid box), so that the tie point position is accurate. See the picture below:

3. Enable location

Need to achieve:

  1. The locating function is automatically enabled on the map page
  2. The central point of the map is the location after successful positioning
  • Both of these are implemented through apis, which are relatively simple; A Message in Chinese is displayed after the location fails
GetLocation () {const mapError = new Map([['Get ipLocation failed.', 'IP location failed '], ['Browser not Support HTML5 geolocation.', 'Browser does not Support native geolocation interface '], [' geolocation Permission denied.', 'Browser denies non-secure domain geolocation request '], ['Get geolocation time out.', 'browser location timeout '], ['Get geolocation failed.',' location failure ']]) this.map.plugin(' amap. geolocation ', () => {const geolocation = new amap. geolocation ({enableHighAccuracy: true, // Whether to use a timeout: ShowButton: false, // Display the marker. ShowMarker: true, // Display the marker at the positioned position after the positioning is successful. ShowCircle: PanToLocation: true, // The location to be located is used as the center of the map after the location is successful. true, SetZoom (16) this.map.setZoom(16) this.map.addControl(geolocation) // Add controls Geolocation. GetCurrentPosition () / / into the page automatically locate AMap. Event. The addListener (geolocation, 'complete', (result) = > {/ / fetch the data is not here, }) amap.event. AddListener (geolocation, 'error', (err) = > {/ / positioning failure error MSG = mapError. Get (err) message) | | err. The message console. The log (MSG); })})}Copy the code

4. Listen for map changes

Listen for map changes through API calls: moving, moving over, zooming, dragging, etc

MapMove () {this.map.on(' mapMove ', () => {this.map.on(' moveEnd ', () => {this.mapmove = false}) () => {this.mapMove = true this.getCenterAddress() // get the address ----})}Copy the code

5. Obtain the detailed address

After the map is moved, use the API to get the detailed address. Let’s start with the two apis:

  1. Amap.placesearch ().searchNearby () searches nearby based on the latitude and longitude of central points, radius and keywords
  2. Amap.geocoder ().getAddress() geocoding and inverse geocoding services for address description and coordinate conversion

🤔 It would seem that the second return is more accurate than the first, but after many trials, the first is more accurate; It is possible to make compatibility between the two approaches, but here is an example of the first

getCenterAddress() { let lnglat = this.map.getCenter() AMap.service('AMap.PlaceSearch', () => { let placeSearch = new AMap.PlaceSearch({ pageSize: 10, pageIndex: 1, children: 1, extensions: 'all', type: 'traffic facilities | | name address information government agencies and social organizations | | building industrial park scenic | | airport departure/arrival | | | ports at the railway station bus station | metro light rail station | | bus station',}) let center = [lnglat LNG, lnglat.lat] placeSearch.searchNearBy('', center, 50, (sta, Result) => {if (sta === 'complete' && result.info === 'OK') {// result.poilist.pois array first item is the exact address})})})}Copy the code

6. Tie point animation 😄

Add a bouncing animation to the tie point after the map is moved, and cancel the animation while moving

Dom: <img SRC =' className 'className={instance.mapmove? 'pinAnima' : '}/> CSS:. PinAnima {animation: bounce 0.5s; } @keyframes bounce { 0% { transform: translateY(0) } 50% { transform: translateY(-20px); } 100% { transform: translateY(0) } }Copy the code

End of the 7.

The idea is not that complicated, think of the map as a box container, and think of the center of the map as the center of the box; When moving the map, go to get the latitude and longitude of [map center point]. When setting a certain position, set the latitude and longitude to [map center point].

There are also some other functions, such as: recommended location Settings, drawing routes, path planning, car driving, radar animation, and other interested can be studied together. In mobile phone positioning will also have some positioning failure, positioning timeout and other problems, can also be studied together.

Give it a thumbs up 😄👍