Calculate Distance Between My Location and a Mapkit Pin on Swift

(Swift) set a 1km radius within my location MapKit

You can do some distance calculations to determine what pins to show.

let pins = Array<MKPointAnnotation>() // This is an empty array, so just use your array of locations or add to this.

if let currentLocation = locationManager.location?.coordinate {

for pin in pins {

let locationMapPoint = MKMapPointForCoordinate(currentLocation)

let pinMapPoint = MKMapPointForCoordinate(pin.coordinate)

let distance = MKMetersBetweenMapPoints(locationMapPoint, pinMapPoint)

if distance >= 5000 && distance <= 10000 {

self.map.addAnnotation(pin)
}
}
}

If you wanted something tidier, you could also do this.

let pins = Array<MKPointAnnotation>()

if let currentLocation = locationManager.location?.coordinate {

let filtered = pins.filter { $0.coordinate.distance(to: currentLocation) >= 5000 && $0.coordinate.distance(to: currentLocation) <= 10000 }

self.map.addAnnotations(filtered)
}

You'll need this extension aswell.

extension CLLocationCoordinate2D {

func distance(to coordinate: CLLocationCoordinate2D) -> Double {

return MKMetersBetweenMapPoints(MKMapPointForCoordinate(self), MKMapPointForCoordinate(coordinate))
}
}

show distance on annotation from current location to another point

Finding Distance between two points(LAT and LONG) on Map :

let coordinate1 = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate2 = CLLocation(latitude: 5.0, longitude: 3.0)
//Decalare distanceInMeters as global variables so that you can show distance on subtitles
let distanceInMeters = coordinate1.distance(from: coordinate2)

Now if you want to show distance in subtitle of annotation then :

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

if annotation is MKUserLocation {
return nil
}

let reuseId = "pinIdentifier"

var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
}
else {
pinView!.annotation = annotation
}

//Adding Subtitle text
let subtitleView = UILabel()
//Decalare distanceInMeters as global variables so that you can show distance on subtitles
subtitleView.text = "\(distanceInMeters)"
pinView!.detailCalloutAccessoryView = subtitleView

return pinView
}

Feel free to comment if further any issue

Swift 4 MapKit check if mark is near to my location

  1. Get visible annotations.
  2. Calculate distance between your position and the mark.

e.g.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let myLocation = locations.first else { return }

let annotationSet = mapView.annotations(in: mapView.visibleMapRect)
for annotation in annotationSet {
guard let annotation = annotation as? MKPointAnnotation else { continue }
let loc = CLLocation(latitude: annotation.coordinate.latitude,
longitude: annotation.coordinate.longitude)
let distance = myLocation.distance(from: loc)
if distance < 10.0 { Show Alert }
}
}
}

swift calculate distance between two locations

From the documentation:

This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth. The resulting arc is a smooth curve and does not take into account specific altitude changes between the two locations.

So you're calculating straight line distance, "as the crow flies", not following roads, which would lead to a longer route, as you're seeing in Maps. You'd need something like MapKit's MKDirectionsRequest to match the route you see in the Maps app. Ray Wenderlich has a good tutorial.

Here's an example I just knocked up that works in a macOS Playground:

//: Playground - noun: a place where people can play

import Cocoa
import MapKit
import CoreLocation

// As we're waiting for completion handlers, don't want the playground
// to die on us just because we reach the end of the playground.
// See https://stackoverflow.com/questions/40269573/xcode-error-domain-dvtplaygroundcommunicationerrordomain-code-1
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let geocoder = CLGeocoder()
geocoder.geocodeAddressString("1 Pall Mall East, London SW1Y 5AU") { (placemarks: [CLPlacemark]? , error: Error?) in
if let placemarks = placemarks {
let start_placemark = placemarks[0]
geocoder.geocodeAddressString("Buckingham Palace, London SW1A 1AA", completionHandler: { ( placemarks: [CLPlacemark]?, error: Error?) in
if let placemarks = placemarks {
let end_placemark = placemarks[0]

// Okay, we've geocoded two addresses as start_placemark and end_placemark.
let start = MKMapItem(placemark: MKPlacemark(coordinate: start_placemark.location!.coordinate))
let end = MKMapItem(placemark: MKPlacemark(coordinate: end_placemark.location!.coordinate))

// Now we've got start and end MKMapItems for MapKit, based on the placemarks. Build a request for
// a route by car.
let request: MKDirectionsRequest = MKDirectionsRequest()
request.source = start
request.destination = end
request.transportType = MKDirectionsTransportType.automobile

// Execute the request on an MKDirections object
let directions = MKDirections(request: request)
directions.calculate(completionHandler: { (response: MKDirectionsResponse?, error: Error?) in
// Now we should have a route.
if let routes = response?.routes {
let route = routes[0]
print(route.distance) // 2,307 metres.
}
})
}
})
}
}

How can I calculate the distance between two points in MkMapview?

You can get lat/lon of the center with:

convertPoint:toCoordinateFromView:

loc1 and loc2 are both CLLocation objs.

CLLocationDistance dist = [loc1 distanceFromLocation:loc2];

So these two tips should help you. if you need some code, let me know :-)



Related Topics



Leave a reply



Submit