简体   繁体   中英

MapKit JS - how to get my current location

I'm try to get my current location on Apple Maps using MapKit JS, but I'm not sure how to do that. The following is the code I have to load the coordinates manually. But I need to be able to have the code to automatically recognize my current coordinate and show it on the Apple Map.

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <script src="https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js"></script>

 <style>
#map {
    width: 100%;
    height: 400px;
}
</style>

</head>

<body>
<div id="map"></div>

<script>
mapkit.init({
    authorizationCallback: function(done) {
        done("API KEY");
    },
    language: "en"
});

var map = new mapkit.Map('map', {
showsMapTypeControl: false,
showsCompass: mapkit.FeatureVisibility.Hidden
 })

var coordinateRegion = new mapkit.CoordinateRegion(
    new mapkit.Coordinate(40.51415196691954, -74.43808765761719),
    new mapkit.CoordinateSpan(1.234, 1.23423)
);
map.region = coordinateRegion;
 </script>
 </body>
 </html>
navigator.geolocation.getCurrentPosition(function(position){
    mylat=position.coords.latitude;
    mylng=position.coords.longitude;
    map.setCenterAnimated(new mapkit.Coordinate(mylat, mylng), true);
});

Clarification as requested: The code above leverages HTML5 Geolocation API. Once the user allows access to their location and it is retrieved, we pass the coordinates to the mapkit element to be set as the center.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM