How do I add maps
Asked on 07/30/2024
1 search
To add maps using MapKit, you can follow these steps:
-
Initialize MapKit JS:
- Add an asynchronous script tag with the MapKit JS source attribute and list your entry point function as the data callback. This will initialize MapKit JS.
<script async src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js" data-callback="initMap" data-token="YOUR_MAPKIT_JS_TOKEN"></script>
-
Create a Map:
- Use the
Map
class to create a map centered around a specific place.
function initMap() { var map = new mapkit.Map("map", { center: new mapkit.Coordinate(37.7749, -122.4194), // Example coordinates for San Francisco span: new mapkit.CoordinateSpan(0.1, 0.1) }); }
- Use the
-
Add Annotations:
- You can add annotations to the map to mark specific places.
var annotation = new mapkit.MarkerAnnotation(new mapkit.Coordinate(37.7749, -122.4194), { title: "San Francisco", subtitle: "California" }); map.addAnnotation(annotation);
-
Use Place IDs:
- Reference places using Place IDs to leverage Apple Maps' data.
function annotatePlace(placeId) { mapkit.search.lookup(placeId, function(error, place) { if (error) { console.error(error); return; } var annotation = new mapkit.MarkerAnnotation(place.coordinate, { title: place.name, subtitle: place.formattedAddress }); map.addAnnotation(annotation); }); }
-
Display Place Details:
- Use the Place Detail API to show detailed information about a place.
function showPlaceDetails(placeId) { mapkit.search.lookup(placeId, function(error, place) { if (error) { console.error(error); return; } // Display place details in your app's UI document.getElementById("place-name").textContent = place.name; document.getElementById("place-address").textContent = place.formattedAddress; }); }
-
Embed Maps in Websites:
- Use the Create a Map tool on the Apple Developer website to generate HTML for embedding maps.
<iframe src="https://maps.apple.com/?q=San+Francisco" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
For more detailed information, you can refer to the session Unlock the power of places with MapKit.