Esse post tem como objetivo apresentar como podemos demarcar uma área qualquer em torno de um ponto utilizando Objective-C.
![]() |
| Figura 1 - Área Delimitada |
A Figura 1 mostra bem o quero apresentar com esse post. Neste figura, existem 7 pontos. O ponto azul simboliza o ponto onde esta o smartphone. Os 4 pontos vermelhos unidos por um quadrado tracejado representam uma área definida em torno do ponto azul.
Imagine a seguinte situação: O ponto azul sendo uma pessoa, os quatro pontos vermelhos unidos por um quadrado tracejado sendo uma área de 1 mil metros quadrados. Você seria capaz de informar para a pessoa diversos tipos de serviços dentro de uma área específica.
Para isso é necessário obter localização do smartphone, isso pode ser realizado implementado o método - (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *) oldLocation do protocolo CLLocationManagerDelegate.
Uma vez que saibamos onde esta o smartphone é possível definir os quatro pontos que definem a área em torno do ponto azul. Para isso deve-se criar uma região utilizando o método MKCoordinateRegion MKCoordinateRegionMakeWithDistance passando o ponto de origem do smartphone e o quanto deseja de distância, para latitude e longitude.
Nesse momento é possível calcular os pontos extremos que definem a área de deseja, calculando o mínimo e o máximo de latitude e longitude. Cada um dos pontos corresponde a seguinte combinação: (mínimoLatitude, mínimoLongitude); (mínimoLatitude, máximoLongitude); (máximoLatitude, máximoLongitude) e (máximoLatitude, mínimoLongitude).
Abaixo segue código em Objective-C capaz de gerar a figura apresentada
TMKViewController.h
#import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> @interface TMKViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> @property (weak, nonatomic) IBOutlet MKMapView *viewMap; @property (weak, nonatomic) IBOutlet UITextField *labelLatitude; @property (weak, nonatomic) IBOutlet UITextField *labelLongitude; - (IBAction) getPosition:(id)sender; @end
TMKViewController.m
#import "TMKViewController.h"
@interface TMKViewController ()
@end
@implementation TMKViewController
@synthesize labelLatitude, labelLongitude, viewMap;
CLLocationManager *locationManager;
CLLocation *currentLocation;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
/*
* INICIALIZANDO LOCATION MANAGER
*/
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate: self];
[locationManager setDesiredAccuracy: kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void) getPosition:(id)sender
{
// GERANDO COORD
CLLocationCoordinate2D theOrigin = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
// GERANDO REGIÃO DE MIL METROS QUADRADOS EM TORNO DO PONTO DE ORIGEM
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(theOrigin, 1000.0, 1000.0);
// CALCULANDO MÍNIMOS E MÁXIMOS DE LATITUDE E LONGITUDE
double minLat = region.center.latitude - (region.span.latitudeDelta / 2.0);
double maxLat = region.center.latitude + (region.span.latitudeDelta / 2.0);
double minLong = region.center.longitude - (region.span.longitudeDelta / 2.0);
double maxLong = region.center.longitude + (region.span.longitudeDelta / 2.0);
// MARCANDO PONTOS NO MAPA
CLLocationCoordinate2D coordinate;
MKPointAnnotation *pointAnnotation = nil;
coordinate = CLLocationCoordinate2DMake( minLat, minLong);
pointAnnotation = [[MKPointAnnotation alloc] init];
[pointAnnotation setCoordinate:coordinate];
[pointAnnotation setTitle:@"Sudoeste"];
[viewMap addAnnotation:pointAnnotation];
coordinate = CLLocationCoordinate2DMake( minLat, maxLong);
pointAnnotation = [[MKPointAnnotation alloc] init];
[pointAnnotation setCoordinate:coordinate];
[pointAnnotation setTitle:@"Sudeste"];
[viewMap addAnnotation:pointAnnotation];
coordinate = CLLocationCoordinate2DMake( maxLat, maxLong);
pointAnnotation = [[MKPointAnnotation alloc] init];
[pointAnnotation setCoordinate:coordinate];
[pointAnnotation setTitle:@"Nordeste"];
[viewMap addAnnotation:pointAnnotation];
coordinate = CLLocationCoordinate2DMake( maxLat, minLong);
pointAnnotation = [[MKPointAnnotation alloc] init];
[pointAnnotation setCoordinate:coordinate];
[pointAnnotation setTitle:@"Noroeste"];
[viewMap addAnnotation:pointAnnotation];
[viewMap setRegion:region animated:YES];
[viewMap setCenterCoordinate:theOrigin];
[viewMap setShowsUserLocation:true];
[viewMap setUserTrackingMode:MKUserTrackingModeFollowWithHeading];
NSLog(@" Noroeste, Lat: %2.4f, Long: %2.4f ", maxLat, minLong);
NSLog(@" Nordeste, Lat: %2.4f, Long: %2.4f ", maxLat, maxLong);
NSLog(@" Sudoeste, Lat: %2.4f, Long: %2.4f ", minLat, minLong);
NSLog(@" Sudeste , Lat: %2.4f, Long: %2.4f ", minLat, maxLong);
}
- (MKOverlayView *)mapView:(MKMapView *)map viewForOverlay:(id <MKOverlay>)overlay
{
MKCircleView *circleView = [[MKCircleView alloc] initWithOverlay:overlay];
circleView.strokeColor = [UIColor redColor];
circleView.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.4];
return circleView;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
currentLocation = newLocation; // ATUALIZANDO VÁRIAVEL QUE GUARDA LOCALIZAÇÃO CORRENTE
if (currentLocation != nil) {
[labelLongitude setText: [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]];
[labelLatitude setText: [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]];
}
}
@end

Nenhum comentário:
Postar um comentário