Как проверить, находятся ли текущие координаты в радиусе других координат - PullRequest
2 голосов
/ 23 января 2012

У меня есть широта и долгота фиксированного местоположения.Я хочу проверить, находится ли другое местоположение (широта и долгота) достаточно близко (50-100 метров) к фиксированному местоположению.Я использую iPhone, чтобы узнать текущее местоположение.

Ответы [ 7 ]

14 голосов
/ 23 января 2012

Метод - distanceFromLocation: из CLLocation это именно то, что вам нужно.

7 голосов
/ 23 января 2012
distanceFromCurrentLocation = [userLocation distanceFromLocation:destinationlocation]/convertToKiloMeter;
if(distanceFromCurrentLocation < 100 && distanceFromLocation > .500)
{
    NSLog(@"Yeah, this place is inside my circle");
}
else
{
    NSLog(@"Oops!! its too far");
}

Это находит расстояние воздуха, или мы можем сказать, только расстояние по прямой линии.
Надеюсь, вы не ищете дорожное расстояние.

1 голос
/ 10 апреля 2015

Добавляя к ответу Deepukjayan, используйте CLLocation, чтобы определить ссылку перед использованием его ответа:

CLLocation *montreal = [[CLLocation alloc] initWithLatitude:45.521731 longitude:-73.628679];
1 голос
/ 23 января 2012

Хотя я проголосовал за пустой стек ... Если вам нужна дополнительная помощь, вот код ..

Будьте CLLocationManagerDelegate и затем в своем классе реализации.

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{


            int distance = [newLocation distanceFromLocation:oldLocation];
            if(distance >50 && distance <100)
            {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Distance"
                                                            message:[NSString stringWithFormat:@"%i meters",distance]
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            [alert release];
            }
        }
    }
1 голос
/ 23 января 2012
CLLocation *location;// = init...;
double distance = [location distanceFromLocation:otherLoc]; //in meters
0 голосов
/ 19 мая 2019

Вот как это сделать в Swift, используя CoreLocation. Вы просто сравниваете 2 разных местоположения, используя метод .distance(from: ) для местоположения типа CLLocation. Убедитесь, что оба местоположения имеют тип CLLocation

import CoreLocation

let someOtherLocation: CLLocation = CLLocation(latitude: someOtherLat,
                                               longitude: someOtherLon)

guard let usersCurrentLocation: CLLocation = locationManager.location else { return }

                                                       // **the distance(from: ) is right here **
let distanceInMeters: CLLocationDistance = usersCurrentLocation.distance(from: someOtherLocation)

if distanceInMeters < 100 {

    // this user is pretty much in the same area as the otherLocation
} else {

   // this user is at least over 100 meters outside the otherLocation
}

в этом нет необходимости, но, возможно, вам нужно сохранить латы и лоны для дальнейшего сравнения. Я знаю, что они мне нужны

let usersCurrentLat: CLLocationDegrees = currentLocation.coordinate.latitude // not neccessary but this is how you get the lat
let usersCurrentLon: CLLocationDegrees = currentLocation.coordinate.longitude // not neccessary but this is how you get the lon

let someOtherLocationLat: CLLocationDegrees = someOtherLocationLocation.coordinate.latitude // not neccessary but this is how you get the lat
let someOtherLocationLon: CLLocationDegrees = someOtherLocationtLocation.coordinate.longitude // not neccessary but this is how you get the lon


let usersLocation: CLLocation = CLLocation(latitude: usersCurrentLat,
                                           longitude: usersCurrentLon)

let otherLocation: CLLocation = CLLocation(latitude: someOtherLocationLat,
                                           longitude: someOtherLocationLon)
0 голосов
/ 22 марта 2017
func distance(from location: CLLocation) -> CLLocationDistance

Документация

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...