javascriptmapkit-js

MapKit JS - Add CoordinateSpan to Coordinate


I'm working with MapKit JS for the first time and have managed to get a dynamically generated simple map working. I would now like to add a CoordinateSpan so I can control the visible area but I'm having trouble working out the syntax. Here's how I'm generating the map currently:

 // Create the "Marker" annotation, setting properties in the constructor.
    const event = new mapkit.Coordinate(40.7484788, -73.9854113);
    const eventAnnotation = new mapkit.MarkerAnnotation(event, {
        color: "red",
        title: "Empire State Building",
        glyphText: "" 
    });

    // Add and show both annotations on the map
    map.showItems([eventAnnotation]);

From another example I've found you can create a CoordinateRegion that includes a CoordinateSpan like the following:

    const mapMarker = new mapkit.CoordinateRegion(
        new mapkit.Coordinate(40.7484788, -73.9854113),
        new mapkit.CoordinateSpan(0.05, 0.05)
    );

    // Create a map in the element whose ID is "map-container"
    const map = new mapkit.Map("map-container");
    map.region = mapMarker;

I've been trying to incorporate the CoordinateRegion into my map code but I keep getting errors. For example I tried changing it to the following:

    // Create the "Marker" annotation, setting properties in the constructor.
    const event = new mapkit.CoordinateRegion(
        new mapkit.Coordinate(40.7484788, -73.9854113),
        new mapkit.CoordinateSpan(0.05, 0.05)
    );


    const eventAnnotation = new mapkit.MarkerAnnotation(event, {
        color: "red",
        title: "Empire State Building",
        glyphText: "" 
    });

    // Add and show both annotations on the map
    map.showItems([eventAnnotation]);

but that just generates an error in the console: Error: [MapKit] Annotation.coordinate expected a Coordinate value.


Solution

  • It seems that you're forgetting to set map.region to event. It's attempting to show items but the coordinates have not been added to the map, which makes sense with the rror.

    You are also attempting to use a CoordinateRegion in place of a Coordinate in MarkerAnnotation. The coordinates for MarkerAnnotation are being used to set the annotation at a specific spot. Try creating a new variable iwth the center of the coordinates and set that as the first parameter for mapkit.MarkerAnnotation.

    // Create the "Marker" annotation, setting properties in the constructor.
    const eventCenter = new mapkit.Coordinate(40.7484788, -73.9854113);
    
    const eventRegion = new mapkit.CoordinateRegion(
        eventCenter,
        new mapkit.CoordinateSpan(0.05, 0.05)
    );
    
    const eventAnnotation = new mapkit.MarkerAnnotation(eventCenter, {
        color: "red",
        title: "Empire State Building",
        glyphText: "" 
    });
    
    map.region = eventRegion;
    
    // Add and show both annotations on the map
    map.showItems([eventAnnotation]);