Amap basic use tutorial

Introduction to the

Take you step by step map display specific location, or to the current location. And the drag-and-drop map interface can query the information around the specified location. Search for surrounding information by keyword.

This tutorial is suitable for beginners.

The demo git address

1. Obtain the key to use Autonavi API

Open the Autonavi development platform, log in, mouse over the picture in the upper right corner, click Application Management to enter my application interface.

Click on the upper right to create a new app.

Add a key to the application.

2. Introduce the map API into the project

Add the entry script tag of the JS API to the page, and replace “the key value you requested” with the key you just requested;

<script type="text/javascript" src="The key values of https://webapi.amap.com/maps?v=1.4.15&key= you application"></script> 
Copy the code

Take the Alita/UMI project as an example. Add the above line to the/SRC /pages/document.ejs file

<! DOCTYPEhtml>
<html>
  <head>.<script type="text/javascript" src="The key values of https://webapi.amap.com/maps?v=1.4.15&key= you application">
    </script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
Copy the code

3. Realize map positioning

The official API can be used as a reference:

Start with a div in your HTML.

<div id="container" style={{ height: '6rem'.width: '100%'}} / >Copy the code

When the page is initialized, define the map:

Map initialization can only obtain city-level information, if you want to obtain the specific location to use the browser positioning. The AUtonavi JS API provides the amap. Geolocation plug-in to implement positioning.

useEffect(() = > {
  const map = new AMap.Map('container', {
    resizeEnable: true.// Whether to monitor map container size changes
    zoom: 16.// Initialize the map hierarchy
  });
  map.plugin(['AMap.Geolocation'].() = > {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true.// Whether to use high precision positioning. Default :true
      timeout: 10000.// Stop positioning after 10 seconds, default: infinity
      zoomToAccuracy: true.// After successful positioning, adjust the map view range to make the positioning position and accuracy range visible in the view. Default: false
    });
    geolocation.getCurrentPosition();

    AMap.event.addListener(geolocation, 'complete'.(data: any) = > console.log(data));
    AMap.event.addListener(geolocation, 'error'.(e: any) = > console.log(e)); }); } []);Copy the code

** is developed locally and may be delayed due to environmental factors. After the project is deployed, the positioning speed will be significantly improved. ** So don’t worry.

So now each time the map initializes it will locate the current location of the terminal. After the map positioning is successful, a complete event will be triggered, with parameters including: positioning success or not, and the latitude and longitude information of the positioning.

If you are not located, you can check whether the location function of the browser and computer is enabled

Tip: Google Chrome may restrict your location in areas with poor reception, making it impossible to locate your current location. Try switching to Firefox.

The above tips are all personal ideas and have nothing to do with me.

4. Add the cover in the current position and the position after dragging

Marker mulch API

map.addControl(geolocation); // Add a location control on the map to obtain and display the longitude and latitude position of the user host
AMap.event.addListener(geolocation, 'complete'.(data: any) = > {
  const marker = new AMap.Marker({
    map,
    position: [data.position.getLng(), data.position.getLat()],
    cursor: 'move'.// Set the drag effect
    raiseOnDrag: true}); });Copy the code

Map. addControl(Geolocation) is important because addControl is a control on the map. Refer to the map control API on the official website

When you drag a map, you want the overlay location icon to always remain in the middle of the map. So we need to listen for map drags.

map.addControl(geolocation); // Add a location control on the map to obtain and display the longitude and latitude position of the user host
AMap.event.addListener(geolocation, 'complete'.(data: any) = > {
  // Omit some code
  const marker = newAMap.Marker({... });// A method is written here
  map.on('moveend'.() = > { mapMove(map, marker) });
});
Copy the code
/** * map drag event */
const mapMove = (map: any, marker: any) = > {
  const mapCenter = map.getCenter();
  marker.setPosition([mapCenter.lng, mapCenter.lat]);
};
Copy the code

5. Query and locate surrounding information

Through the fourth point, we have been able to obtain the longitude and latitude and city information of the current location through positioning.

AMap.event.addListener(geolocation, 'complete'.(data: any) = >{...// Omit some code here
  getCurrentAddr([data.position.getLng(), data.position.getLat()], map);
})
Copy the code

Input prompt plug-in, according to the keyword to obtain the relevant POI information in the corresponding city, can refer to the official website – input prompt and POI search module.

AMap.service(['AMap.PlaceSearch'].() = > {
  // Construct the location query class
  const placeSearch = new AMap.PlaceSearch({
    pageSize: 20.// Display the number of results in a single page
    pageIndex: 1./ / page
    // city: "010", // city of interest
    citylimit: true.// Whether to force search within the set city
    children: 1.// map, // display the resulting map instance
    // panel: "panel", // The result list will be displayed in this container.
    autoFitView: true.// Whether to automatically adjust the map field of view so that all drawn Marker points are visible in the viewport
  });
  placeSearch.searchNearBy(
    ' ',
    lnglat,
    200.(status: string, result: { poiList: { pois: React.SetStateAction<never[]> } }) = > {
      console.log(status, result); }); });Copy the code

If you want to re-query the center of the map after each map drag. You can add the getCurrentAddr method to the mapMove method.

6. Maps show specific cities

When there is a need to display specific city information, such as Fuzhou, Xiamen, etc. Instead of having a detailed address. So how to deal with it.

Here provides a program, may not be the best, only for reference.

Search through the city to find the next level of administrative data. If there is data, then get the first data, get the latitude and longitude to display on the map.

See the official website – for sub-administrative information

AMap.plugin('AMap.DistrictSearch'.() = > {
  var districtSearch = new AMap.DistrictSearch({
    // Administrative level corresponding to the keyword. Country indicates a country
    level: 'province'.// Displays the level of the lower administrative level, with 1 indicating the return of the lower administrative level
    subdistrict: 1});// Search for all provinces/municipalities
  districtSearch.search('guangzhou'.(status: any, result: any) = > {
    console.log(result);
    // If the query succeeds, result indicates the corresponding administrative district
    if (status === 'complete') {
      const districtList = result.districtList[0];
      const center = [districtList.center.lng, districtList.center.lat];
      // Locate to the specified city
      const mapTwo = new AMap.Map('con', {
        resizeEnable: true.// Whether to monitor map container size changes
        zoom: 16.// Initialize the map hierarchycenter, }); }}); });Copy the code

So far, the map has been perfectly positioned to the city we want. If we want to add coverings in the center of a specific city for display, and query the surrounding information of a specific city.

7. Display cladding for specific cities

// Locate to the specified city
const mapTwo = new AMap.Map('con', {
  resizeEnable: true.// Whether to monitor map container size changes
  zoom: 16.// Initialize the map hierarchy
  center,
});

const marker = new AMap.Marker({
  map: mapTwo,
  position: center,
  // Set whether drag can be used
  // draggable: true,
  cursor: 'move'.// Set the drag effect
  raiseOnDrag: true}); mapTwo.on('moveend'.() = > {
  const mapCenter = mapTwo.getCenter();
  marker.setPosition([mapCenter?.lng, mapCenter?.lat]);
});
Copy the code

And the overlay can be remodified as you drag the map.

Writing is not easy, give a star then go ~