AMap JSAPI Skills

repository·main·Indexed 40 days ago

https://github.com/amap-web/amap-skills

A collection of structured knowledge files and AI programming skill packages designed to enhance AI coding assistants (such as Cursor, Claude, and Cline) when working with the AMap JavaScript API v2.0. It provides guidance on map initialization, overlay drawing, layer management, LBS services, and GeometryUtil for calculating distances, areas, and geometric intersections.

Tokens
72.6K
Snippets
168
Records
302
Agent score
50%

What's inside AMap JSAPI Skills

  1. How the JSAPI Event system works

    main

    The JSAPI features a complete event system where all types of instances (Map, Layers, Overlays, etc.) implement an event interface. This interface allows you to bind, remove, and manage event callbacks for any instance object. In version 2.0, all instance types use the on/off pattern for event binding and removal.

    // Example: Binding a click event to a map instance
    function onClick(e) {
        console.log(e);
    }
    map.on('click', onClick);
    
    // Example: Binding a mousemove event to a polygon overlay
    polygon.on('mousemove', console.log);
  2. Retrieve bus station details by ID or Keyword

    main

    You can retrieve specific bus station details using AMap.LineSearch.

    Search by Station ID

    Provide the unique identifier for a bus station to retrieve its details.

    Search by Keyword

    Provide a bus station name. If searching for multiple keywords, separate them with a pipe |.

    Result Statuses

    When the search completes, the status field indicates the outcome:

    • complete: The result field contains a LineSearchResult object.
    • error: The result field contains error information (info).
    • no_data: No results were found for the query.
  3. Layer Management

    main

    The JSAPI supports various layer types for different visualization needs:

    • Official Layers: Standard, Satellite, RoadNet, Buildings, and District layers.
    • Standard Layers: WMS, WMTS, and MapboxVectorTileLayer.
    • Custom Layers: For advanced integration, you can use CanvasLayer, GLCustomLayer (for Three.js integration), HeatMap, VectorLayer, LabelsLayer, or ImageLayer.
  4. Animate markers with AMap.MoveAnimation

    main

    The AMap.MoveAnimation plugin provides base classes for animating markers along lines or paths (e.g., for real-time vehicle tracking or playback). Marker, Text, and LabelMarker inherit from this implementation.

    Note: You must load the plugin using AMap.plugin('AMap.MoveAnimation', ...) before using these methods.

    moveTo

    Moves a marker to a specific position over a set duration.

    • targetPosition: LngLat | Vector - The destination.
    • opts.duration: number - Duration in milliseconds.
    • opts.easing: EasingCallback - Timing function.
    • opts.autoRotation: boolean - Whether the marker rotates to follow the path.

    moveAlong

    Moves a marker along a predefined path.

    • path: Array<LngLat | Vector | MoveAlongObj> - The path array.
    • opts.duration: number | AnimationCallback - Duration per segment.
    • opts.circlable: boolean - Whether the animation loops.
    • opts.delay: number | AnimationCallback - Delay before starting.
    • opts.aniInterval: number - Interval between complete animations.
    • opts.autoRotation: boolean - Whether the marker rotates to follow the path.
    // Example: moveTo
    AMap.plugin('AMap.MoveAnimation', function() {
        const animationMarker = new AMap.Marker({
            position: new AMap.LngLat(116.397389, 39.909466),
        });
        animationMarker.moveTo([116.397389, 39.909466], {
            duration: 1000,
            delay: 500,
        });
    });
    
    // Example: moveAlong with custom data
    const path = [
        new AMap.LngLat(116.397389, 39.909466),
        new AMap.LngLat(116.379707, 39.968168),
        new AMap.LngLat(116.434467, 39.95001),
        new AMap.LngLat(116.46365, 39.979481),
        new AMap.LngLat(116.397389, 39.909466),
    ];
    const customData = [
        { position: path[0], duration: 200 },
        { position: path[1], duration: 400 },
        { position: path[2], duration: 600 },
        { position: path[3], duration: 800 },
        { position: path[4], duration: 1000 },
    ];
    
    AMap.plugin('AMap.MoveAnimation', function() {
        const animationMarker = new AMap.Marker({
            position: new AMap.LngLat(116.397389, 39.909466),
            angle: 90,
        });
        animationMarker.moveAlong(customData);
    });
  5. Manage layer properties (zIndex, opacity, visibility, zooms)

    main

    Most layer types in the JSAPI support the following methods to manage their state:

    • Visibility: Use .show() to make the layer visible or .hide() to hide it.
    • Layer Order: Use .getzIndex() to retrieve the current order and .setzIndex(number) to change it. Higher numbers appear on top.
    • Transparency: Use .getOpacity() to retrieve the current value and .setOpacity(number) to set it (range [0, 1]).
    • Zoom Range: Use .getZooms() to retrieve the current range and .setZooms(range) to update it (where range is [min, max]).
  6. How LayerGroup works for batch layer operations

    main

    A LayerGroup is used to wrap multiple layer instances, allowing you to perform batch operations instead of iterating through layers manually to set common properties.

    Key behaviors:

    • Automatic Map Management: Once you call setMap(map) on a LayerGroup, any new layer added to that group will automatically be assigned to that map. Conversely, removing a layer from the group also removes it from the map.
    • Batch Event Binding: If you attach an event listener to the group using .on(), the event will be applied to all supported layers within the group.
    • Batch Styling: You can use setOptions to update properties like visibility, opacity, and z-index for all layers in the group simultaneously.
    // Example concept of LayerGroup usage
    const group = new LayerGroup([layer1, layer2]);
    group.setMap(map);
    // New layers added to the group will automatically appear on the map
    group.addLayer(newLayer);
    // Batch update visibility
    group.setOptions({ visible: false });
  7. How GLCustomLayer works with Three.js for 3D rendering

    main

    The AMap.GLCustomLayer allows for high-performance 3D scene rendering by integrating with WebGL/Three.js.

    Key Lifecycle Methods

    • init(gl): Called once during layer creation. Use this to initialize your Three.js Renderer, Scene, and Camera. Crucial: Set renderer.autoClear = false to ensure the base map remains visible. Use the provided gl context for the renderer.
    • render(): Called every frame. You must synchronize your camera with the map's camera using map.customCoords.getCameraParams().

    Critical Implementation Requirements

    1. Coordinate Conversion: Use map.customCoords.lngLatsToCoords() to convert geographic coordinates to 3D space coordinates. This must be called before retrieving camera parameters.
    2. Camera Synchronization: In the render loop, apply near, far, fov, position, up, and lookAt from getCameraParams() to your camera. For 2D maps, use an Orthographic camera and the corresponding 2D parameters.
    3. State Management: You must call renderer.resetState() both before and after your Three.js rendering logic to prevent state corruption between the map and your custom layer.
    4. Center Reset: Call customCoords.setCenter([lng, lat]) in the render loop to prevent object offset issues when using other map capabilities like LOCA visualization.
    // ... setup map and customCoords ...
    var data = customCoords.lngLatsToCoords([[116.52, 39.79], [116.54, 39.79]]);
    
    var gllayer = new AMap.GLCustomLayer({
      zIndex: 10,
      init: (gl) => {
        camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 100, 1 << 30);
        renderer = new THREE.WebGLRenderer({ context: gl });
        renderer.autoClear = false; // Required to see the map
        scene = new THREE.Scene();
        // ... setup lights and meshes ...
      },
      render: () => {
        renderer.resetState(); // Reset state before rendering
        customCoords.setCenter([116.52, 39.79]); // Reset center to prevent offset
        
        var { near, far, fov, up, lookAt, position } = customCoords.getCameraParams();
        camera.near = near;
        camera.far = far;
        camera.fov = fov;
        camera.position.set(...position);
        camera.up.set(...up);
        camera.lookAt(...lookAt);
        camera.updateProjectionMatrix();
    
        renderer.render(scene, camera);
        renderer.resetState(); // Reset state after rendering
      },
    });
    map.add(gllayer);
  8. Drawing Overlays and Markers

    main

    Overlays allow you to add visual elements to the map:

    • Markers: Use Marker for basic points, LabelMarker for high-density scenarios requiring avoidance, or Text/Icon for specific styling.
    • Vector Graphics: Draw shapes such as Polyline (paths/lines), Polygon (areas/faces), Circle (ranges), Ellipse, and Rectangle.
    • Information Display: Use InfoWindow to show detailed information popups.
    • Interactivity: Use ContextMenu to implement custom right-click menus on the map or specific overlays.
  9. Routing Implementation Best Practices and Constraints

    main

    When implementing routing services in AMap, keep the following technical constraints and tips in mind:

    General Constraints:

    • Start/End Formats: Supports both coordinate arrays [lng, lat] and keyword objects {keyword: '...', city: '...'}.
    • Waypoints: Most routing services support a maximum of 16 waypoints (途经点).

    Service-Specific Tips:

    • Driving: Use showTraffic: true to visualize real-time traffic. Use the number parameter to account for vehicle restrictions.
    • Cycling: Best suited for short to medium distances; very long distances may return no results. It is recommended to use orange colors to distinguish cycling from driving (blue) or walking (green).
    • Walking: Often implemented using strokeStyle: 'dashed' in custom Polyline drawings to visually differentiate the path.
    • Rendering: If you provide map and panel in the constructor, the service will automatically draw the route and populate the results list.
  10. Map Control and View Interaction

    main

    You can control the map's lifecycle and visual state using the following concepts:

    • Lifecycle Management: Handle the flow of load, creating the Map instance, and calling destroy to clean up resources.
    • View Interaction: Control the camera using:
      • zoom: Zooming in and out.
      • center: Panning the map.
      • pitch: Adjusting the tilt/pitch angle.
      • rotation: Rotating the map view.
  11. LBS Services and Plugins

    main

    The API provides several Location Based Services (LBS) through plugins:

    • Geocoder: Convert between addresses and geographic coordinates (Geocoding/Reverse Geocoding).
    • Routing: Plan paths for Driving, Walking, Transferring (Public Transit), or Riding.
    • Search: Perform POI (Point of Interest) searches and use AutoComplete for input suggestions.
    • Geolocation: Retrieve the user's current location.