obtain userLocation from mapView ios - ios

I want to retrieve the current position and send it with a POST request to a server.
I use mapView.userLocation.location.coordinate but it doesn't work and shows always 0.0 for lat and 0.0 for lng.
This is .h of my controller:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface CustomViewController : UIViewController
<MKMapViewDelegate>
#property NSMutableArray * shops;
#property (strong, nonatomic) IBOutlet UIActivityIndicatorView *loadingIcon;
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#end
and this .m :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_mapView.showsUserLocation = YES;
_mapView.delegate = self;
_shops = [[NSMutableArray alloc] init];
[_loadingIcon startAnimating];
CLLocationCoordinate2D coordinate;
coordinate = _mapView.userLocation.location.coordinate;
NSNumber *lat = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *lng = [NSNumber numberWithDouble:coordinate.longitude];
//here the post method
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:lat,lng, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
.....
NSLog(#"posizione %#", jsonString);
}
in Log I always have 0.0 0.0.
I have this method too:
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation: (MKUserLocation *)userLocation
{
[_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
userLocation.title = #"Posizione attuale";
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000);
[_mapView setRegion:region animated:YES];
NSLog(#"lat %f", (double)userLocation.location.coordinate.latitude);
}
and in this case the log shows the current position.
Someone have an idea?

Related

How to find road distance between two Coordinates and make a polyline between same points?

I want to find road distance between two coordinates. Firstly i am taking source and destination from user and then using googleMap api i find the coordinates.
I am able to find coordinates and air distance but i am unable to find road distance and draw a polyline between them. Every method available on google is for older xcode and not supported on xcode 6.
Method i am using for finding coordinates
-(CLLocationCoordinate2D)FindCoordinates:(NSString *)place
{
NSString *addresss = place;
NSString *esc_addr = [addresss stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: #"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
NSDictionary *googleResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *resultsDict = [googleResponse valueForKey: #"results"]; // get the results dictionary
NSDictionary *geometryDict = [ resultsDict valueForKey: #"geometry"]; // geometry dictionary within the results dictionary
NSDictionary *locationDict = [ geometryDict valueForKey: #"location"]; // location dictionary within the geometry dictionary
// nslo (#”– returning latitude & longitude from google –”);
NSArray *latArray = [locationDict valueForKey: #"lat"]; NSString *latString = [latArray lastObject]; // (one element) array entries provided by the json parser
NSArray *lngArray = [locationDict valueForKey: #"lng"]; NSString *lngString = [lngArray lastObject]; // (one element) array entries provided by the json parser
myLocation.latitude = [latString doubleValue]; // the json parser uses NSArrays which don’t support “doubleValue”
myLocation.longitude = [lngString doubleValue];
return myLocation;
}
method i am using for finding distance
-(IBAction)getLocation:(id)sender
{
sourceLocation = [self FindCoordinates:source1.text];
NSLog(#"%#",[NSString stringWithFormat:#"Source lat:%f Source lon:%f",sourceLocation.latitude,sourceLocation.longitude]);
destinationLocation = [self getMe:destination1.text];
NSLog(#"%#",[NSString stringWithFormat:#"Desti lat:%f Desti lon:%f",destinationLocation.latitude,destinationLocation.longitude]);
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:sourceLocation.latitude longitude:sourceLocation.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:destinationLocation.latitude longitude:destinationLocation.longitude];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSLog(#"%#",[NSString stringWithFormat:#"Distance iin KMeteres %f",distance/1000]); // Gives me air distance
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ]; // Not able to modify these cordinates
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:#""];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:#""];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeWalking];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
NSLog(#"response = %#",response);
NSArray *arrRoutes = [response routes];
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[map addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
NSLog(#"Total Steps : %lu",(unsigned long)[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Rout Instruction : %#",[obj instructions]);
NSLog(#"Rout Distance : %f",[obj distance]);
}];
}];
}];
}
How can draw a polyline also.
You have to use MKPolylineRenderer for iOS 8
Following is the code for adding MKPolyline by tapping on locations may you get help.
Pin.h
#import <Foundation/Foundation.h>
#import MapKit;
#interface Pin : NSObject <MKAnnotation>
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate;
#end
Pin.m
#import "Pin.h"
#implementation Pin
- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate {
self = [super init];
if (self) {
_coordinate = newCoordinate;
_title = #"Hello";
_subtitle = #"Are you still there?";
}
return self;
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#import MapKit;
#interface ViewController : UIViewController <MKMapViewDelegate>
#end
ViewController.m
#import "ViewController.h"
#import "Pin.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) NSMutableArray *allPins;
#property (nonatomic, strong) MKPolylineRenderer *lineView;
#property (nonatomic, strong) MKPolyline *polyline;
- (IBAction)drawLines:(id)sender;
- (IBAction)undoLastPin:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.allPins = [[NSMutableArray alloc]init];
// add a long press gesture
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(addPin:)];
recognizer.minimumPressDuration = 0.5;
[self.mapView addGestureRecognizer:recognizer];
}
// let the user add their own pins
- (void)addPin:(UIGestureRecognizer *)recognizer {
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
// convert touched position to map coordinate
CGPoint userTouch = [recognizer locationInView:self.mapView];
CLLocationCoordinate2D mapPoint = [self.mapView convertPoint:userTouch toCoordinateFromView:self.mapView];
// and add it to our view and our array
Pin *newPin = [[Pin alloc]initWithCoordinate:mapPoint];
[self.mapView addAnnotation:newPin];
[self.allPins addObject:newPin];
[self drawLines:self];
}
- (IBAction)drawLines:(id)sender {
// HACK: for some reason this only updates the map view every other time
// and because life is too frigging short, let's just call it TWICE
[self drawLineSubroutine];
[self drawLineSubroutine];
}
- (IBAction)undoLastPin:(id)sender {
// grab the last Pin and remove it from our map view
Pin *latestPin = [self.allPins lastObject];
[self.mapView removeAnnotation:latestPin];
[self.allPins removeLastObject];
// redraw the polyline
[self drawLines:self];
}
- (void)drawLineSubroutine {
// remove polyline if one exists
[self.mapView removeOverlay:self.polyline];
// create an array of coordinates from allPins
CLLocationCoordinate2D coordinates[self.allPins.count];
int i = 0;
for (Pin *currentPin in self.allPins) {
coordinates[i] = currentPin.coordinate;
i++;
}
// create a polyline with all cooridnates
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:self.allPins.count];
[self.mapView addOverlay:polyline];
self.polyline = polyline;
// create an MKPolylineView and add it to the map view
self.lineView = [[MKPolylineRenderer alloc]initWithPolyline:self.polyline];
self.lineView.strokeColor = [UIColor redColor];
self.lineView.lineWidth = 5;
// for a laugh: how many polylines are we drawing here?
self.title = [[NSString alloc]initWithFormat:#"%lu", (unsigned long)self.mapView.overlays.count];
}
- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
return self.lineView;
}
#end
Get distance by
CLLocationDistance dist = [from distanceFromLocation:current];

iOS 7 Reverse Geocoding Using Mapkit

I am making an app with a map that shows the location that you type in a text field, also if you move around the map it displays on the text field the address of the location that you are looking at.
When I move around the map it display the address in the text field and shows only the street, but I was wondering if it is possible to show the address as is used in Colombia, for example: Carrera 1 # 18A - 12.If you type the address like the example in the text field it works and it founds it in the map, but does not display the address in the text field as I want.
Here is the code I am using.
If somebody can help me i would really appreciate it.
Thanks
.h file
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#interface ViewControllerMapaDestinoCasa : UIViewController < UITextFieldDelegate, MKMapViewDelegate>
#property (strong, nonatomic) CLLocation *ubicacionSeleccionada;
#property (strong, nonatomic) NSMutableDictionary *lugarDiccionario;
#property (strong, nonatomic) IBOutlet MKMapView *mapa;
#property (strong, nonatomic) IBOutlet UITextField *textFieldDireccion;
- (IBAction)botonUbicacionActual:(id)sender;
#end
.m file
#import "ViewControllerMapaDestinoCasa.h"
#interface ViewControllerMapaDestinoCasa ()
#end
#implementation ViewControllerMapaDestinoCasa
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.textFieldDireccion.delegate = self;
self.mapa.delegate = self;
self.lugarDiccionario = [[NSMutableDictionary alloc] init];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 4.609886;
zoomLocation.longitude= -74.08205;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 1609.344,1609.344);
[self.mapa setRegion:viewRegion animated:YES];
}
- (IBAction)botonUbicacionActual:(id)sender {
[self updatePlaceDictionary];
[self updateMaps];
}
- (void)updatePlaceDictionary {
[self.lugarDiccionario setValue:self.textFieldDireccion.text forKey:#"Street"];
[self.lugarDiccionario setValue:#"Bogotá" forKey:#"City"];
[self.lugarDiccionario setObject:#"Colombia" forKey:#"Country"];
}
- (void)updateMaps {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressDictionary:self.lugarDiccionario completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
[self.mapa setCenterCoordinate:coordinate animated:YES];
} else {
NSLog(#"error");
}
}];
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
self.ubicacionSeleccionada =
[[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude
longitude:mapView.centerCoordinate.longitude];
[self performSelector:#selector(delayedReverseGeocodeLocation)
withObject:nil
afterDelay:0.3];
}
- (void)delayedReverseGeocodeLocation {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self reverseGeocodeLocation];
}
- (void)reverseGeocodeLocation {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:self.ubicacionSeleccionada completionHandler:^(NSArray *placemarks, NSError *error) {
if(placemarks.count){
NSDictionary *dictionary = [[placemarks objectAtIndex:0] addressDictionary];
[self.textFieldDireccion setText:[dictionary valueForKey:#"Street"]];
}
}];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
Here is the code I use to get the full address, if I understood your question correctly.
[geocoder reverseGeocodeLocation:touchLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (!error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
// Update annotation with address
self.person.address.state = placemark.administrativeArea;
self.person.address.city = placemark.locality;
NSString *placemarkAddress;
//Accounts for the possibility of the number or street being null
if (placemark.subThoroughfare && placemark.thoroughfare){
placemarkAddress = [NSString stringWithFormat:#"%# %#",placemark.subThoroughfare, placemark.thoroughfare];
}
else if (placemark.thoroughfare){
placemarkAddress = placemark.thoroughfare;
}
self.person.address.street1 = placemarkAddress;
self.person.address.zip = placemark.postalCode;
}
else {
//Error
}
}];

IOS parent ViewController original coordinate missed after getting child ViewCOntroller Data

I have implemented the module to pass the values from child viewController (SliderViewController ) to master viewController (MapViewController) but when it comes to the implementation, the position just added is lost and hence the array of coordinates cannot be added and hence presented? Besides saving the coordinates into the text file and reload, are there any other alternatives to save the array of coordinates ?
The below is my working:
ChildViewCOntroller
SliderViewController.h
#import <UIKit/UIKit.h>
#import "EFCircularSlider.h"
#protocol SliderViewControllerDelegate <NSObject>
- (void)passData:(float )itemVertical : (float )itemCircular ;
#end
#interface SliderViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *uiValue;
#property (strong, nonatomic) IBOutlet UISlider *uiSlider;
#property (strong, nonatomic) IBOutlet UIButton *btnReset;
#property (strong, nonatomic) IBOutlet UILabel *uiValue2;
#property (strong, nonatomic) EFCircularSlider* circularSlider;
#property (nonatomic) float verticalSliderValue;
#property (nonatomic) float circleSliderValue;
#property (nonatomic) id <SliderViewControllerDelegate> delegate;
- (IBAction)reset:(id)sender;
- (IBAction)sliderChange:(id)sender;
- (void)buttonClicked: (id)sender;
#end
SliderViewController.m
#import "SliderViewController.h"
#import <AudioToolbox/AudioServices.h>
#import "MapViewController.h"
#interface SliderViewController (){
NSString *valueV;
NSString *valueC;
}
#end
#implementation SliderViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_uiSlider.minimumValue = 0.0;
_uiSlider.maximumValue = 100.0;
[_uiSlider removeConstraints:_uiSlider.constraints];
[_uiSlider setTranslatesAutoresizingMaskIntoConstraints:YES];
float value = M_PI * -0.5 ;
_uiSlider.transform = CGAffineTransformMakeRotation(value);
CGRect sliderFrame = CGRectMake(60, 300, 100, 100);
_circularSlider = [[EFCircularSlider alloc] initWithFrame:sliderFrame];
[_circularSlider addTarget:self action:#selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_circularSlider];
[_circularSlider setCurrentValue:10.0f];
[_uiSlider setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.5]];
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
CGFloat height = CGRectGetHeight(screen);
float scale = [[UIScreen mainScreen] scale];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake( 0, 450 ,width/2, 20);
[button setTitle:#"OK" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:16.0];
button.titleLabel.adjustsFontSizeToFitWidth = TRUE;
[button setBackgroundColor:[UIColor orangeColor]];
[button addTarget: self
action: #selector(buttonClicked:)
forControlEvents: UIControlEventTouchDown];
[self.view addSubview:button];
}
- (void) buttonClicked: (id)sender
{
NSLog( #"Button clicked." );
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)valueChanged:(EFCircularSlider*)slider {
self.uiValue2.text = [NSString stringWithFormat:#"%.02f", slider.currentValue ];
_circleSliderValue = slider.currentValue;
valueC = self.uiValue2.text;
if(slider.currentValue > 20.0 && slider.currentValue < 30.0 ){
AudioServicesPlaySystemSound(1003);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
- (IBAction)reset:(id)sender {
[self writeToTextFile:valueV :valueC];
MapViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"MapViewController"];
sliderVC.verticalSliderValue = _uiSlider.value;
sliderVC.circleSliderValue =_circularSlider.currentValue;
[sliderVC passData:_uiSlider.value :_circularSlider.currentValue ];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void) writeToTextFile:(NSString*) values : (NSString*) values2 {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/slider.txt",documentsDirectory];
NSString *content = [NSString stringWithFormat:#"%#%#%#%#", values , #"\n" , values2 , #"\n" ];
[content writeToFile:fileName
atomically:YES
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSLog(#"%#",documentsDirectory);
[self displayContent];
}
-(void) displayContent{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/slider.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
NSLog(#"%#",content);
}
- (IBAction)sliderChange:(id)sender {
UISlider *slider = (UISlider *)sender;
NSString *newValue = [NSString stringWithFormat:#"%.2f" , slider.value];
_verticalSliderValue = slider.value;
self.uiValue.text = newValue;
valueV = self.uiValue.text;
if(slider.value > 30 && slider.value < 50){
AudioServicesPlaySystemSound(1003);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
MasterViewController
MapViewController.h
#import <MessageUI/MessageUI.h>
#import <GoogleMaps/GoogleMaps.h>
#import <UIKit/UIKit.h>
#import "SliderViewController.h"
#interface MapViewController : UIViewController<GMSMapViewDelegate , SliderViewControllerDelegate>{
}
#property (nonatomic) float verticalSliderValue;
#property (nonatomic) float circleSliderValue;
#end
MapViewCntroller.m
#import "MapViewController.h"
#import "CheckPoints.h"
#import "NSURLRequestSSL.h"
#import "ToastView.h"
#interface MapViewController () {
GMSMapView *mapView_;
NSMutableArray *array;
GMSCameraPosition *camera;
NSArray *_styles;
NSArray *_lengths;
NSArray *_polys;
double _pos, _step;
CLLocationCoordinate2D p;
}
#end
#implementation MapViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self getTime];
array = [[NSMutableArray alloc] init];
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.uisplatch
camera = [GMSCameraPosition cameraWithLatitude:22.2855200
longitude:114.1576900
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.delegate = self;
mapView_.myLocationEnabled = YES;
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
// mapView_.delegate = self;
self.view = mapView_;
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
marker.title = #"My place";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// defaults
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
if(latitide!=0.00&&longitude!=0.00) {
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
}
if(desp.length > 0 ){
marker.title = desp;
}
marker.snippet = #"HK";
marker.map = mapView_;
}
...
- (void)passData:(float )value1 : (float )valueCiruclar
{
NSLog(#"This was returned from ViewControllerB %ff",value1);
NSLog(#"This was returned from ViewControllerSlider %ff",valueCiruclar);
[mapView_ clear];
NSLog(#"This was map received");
CheckPoints *myCar=[[CheckPoints alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
[myCar setLatitude:latitide];
[myCar setLongitude:longitude];
[myCar setDesp:desp];
[myCar setState:[desp length] > 0 ? 0 : 1];
[CarArray addObject:myCar];
NSLog(#"This was returned lat from ViewControllerB %ff",[myCar getLatitude]);
NSLog(#"This was returned longi from ViewControllerSlider %ff",[myCar getLongitude]);
NSLog(#"This was returned desp from ViewControllerB %#",[myCar getDesp]);
NSLog(#"This was returned state from ViewControllerSlider %i",[myCar getState]);
lastChk = CarArray.lastObject;
[self writeToTextFile:[NSString stringWithFormat:#"%#%#%#%#%#%#", lastChk.getDesp , #"\n",[NSString stringWithFormat:#"%f", lastChk.getLatitude],
#"\n", [NSString stringWithFormat:#"%f", lastChk.getLongitude], #"\n" ]];
NSLog(#"This was map arraoy count #%i" , [CarArray count]);
for (int i = 0; i < [CarArray count]; i++) {
CheckPoints *current = [CarArray objectAtIndex:i];
if(current.getLatitude != lastChk.getLatitude && current.getLongitude != lastChk.getLongitude){
[current setState:1];
NSString* previousTitle = [NSString stringWithFormat:#"%#%#", #"Checkpoint" ,[NSString stringWithFormat:#"%i", i+1]];
[current setDesp:previousTitle];
}
}
[self addMarkers];
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
p = coordinate;
SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"SliderViewController"];
sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentViewController:sliderVC animated:YES completion:NULL];
}
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate
{
p = coordinate;
SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"SliderViewController"];
sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
**[sliderVC setDelegate:self]**
[self presentViewController:sliderVC animated:YES completion:NULL];
}
and
- (IBAction)reset:(id)sender
{
[self writeToTextFile:valueV :valueC];
[self.delegate passData:_uiSlider.value :_circularSlider.currentValue ];
[self dismissViewControllerAnimated:YES completion:nil];
}
Don't create a new instance. What you need is just use delegate.

How to set standard cityOutlet in geocoding?

I'm making a application where the user sets the adres in an UITextField and gets a location on the map.
I want the cityOutlet to be invisible but be fixed at the city 'Amsterdam'.
Is there an way to do this? I couldn't find a way to fix this, or am I stupid..
#property (weak, nonatomic) IBOutlet UITextField *addressOutlet;
#property (weak, nonatomic) IBOutlet UITextField *cityOutlet;
#property (strong, nonatomic) CLLocation *selectedLocation;
#property (strong, nonatomic) NSMutableDictionary *placeDictionary;
- (void)viewDidLoad
{
[super viewDidLoad];
self.addressOutlet.delegate = self;
self.cityOutlet.delegate = self;
self.mapView.delegate = self;
self.placeDictionary = [[NSMutableDictionary alloc] init];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 40.740848;
zoomLocation.longitude= -73.991134;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 1609.344,1609.344);
[self.mapView setRegion:viewRegion animated:YES];
}
- (void)updatePlaceDictionary {
[self.placeDictionary setValue:self.addressOutlet.text forKey:#"Street"];
[self.placeDictionary setValue:self.cityOutlet.text forKey:#"City"];
}
- (void)updateMaps {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
[self.mapView setCenterCoordinate:coordinate animated:YES];
} else {
NSLog(#"error, geen adres gevonden");
}
}];
}
- (void)delayedReverseGeocodeLocation {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self reverseGeocodeLocation];
}
- (void)reverseGeocodeLocation {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:self.selectedLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if(placemarks.count){
NSDictionary *dictionary = [[placemarks objectAtIndex:0] addressDictionary];
[self.addressOutlet setText:[dictionary valueForKey:#"Street"]];
[self.cityOutlet setText:[dictionary valueForKey:#"City"]];
}
}];
}
- (IBAction)submitTapped:(id)sender {
[self updatePlaceDictionary];
[self updateMaps];
}
in -viewDidLoad to hide the UILabel outlet and set its text try this:
self.cityOutlet.text = #"Amsterdam";
self.cityOutlet.hidden = YES;
Then comment out/remove this line in your reverse geocode location method:
//[self.cityOutlet setText:[dictionary valueForKey:#"City"]];
Alternatively, if you're not using the cityOutlet label for anything but holding a string, try just using an NSString property in your implementation file instead of the outlet.
#property (nonatomic, strong) NSString* cityName;

Passing Co-ordinates from one view to another

Now i am updating the code with the perfect output. This may help my friends to place the correct markers.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import
#import "fetchurl.h"
#import
#interface placevcViewController : UIViewController
{
CLLocationDegrees lat;
CLLocationDegrees lng;
CLLocationCoordinate2D local;
}
-(id)init;
-(void)location:(CLLocationManager *)address;
#property (nonatomic, strong) NSDictionary *location;
#property (strong, nonatomic) UITextField *addressfeild;
#property (strong, nonatomic) fetchurl *fu;
#property (strong, nonatomic) GMSMapView *map;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) GMSCameraPosition *camera;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "placevcViewController.h"
#interface placevcViewController ()
#end
#implementation placevcViewController
#synthesize addressfeild, map,fu,locationManager,camera;
-(id)init
{
self = [super init];
location = [[NSDictionary alloc] initWithObjectsAndKeys:#"0.0",#"lat",#"0.0",#"lng",#"Null Island",#"adress",#"NULL Home",#"name", nil];
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
lat = locationManager.location.coordinate.latitude;
lng = locationManager.location.coordinate.longitude;
local = CLLocationCoordinate2DMake(lat, lng);
fu = [[fetchurl alloc]init];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude: lng zoom:12];
map = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:camera];
[self.view addSubview:map];
map.settings.myLocationButton = YES;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(200, 65, 100, 40);
[button setTitle:#"SEARCH" forState:UIControlStateNormal];
[button addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
addressfeild = [[UITextField alloc] initWithFrame:CGRectMake(10, 68, 200, 30)];
addressfeild.placeholder = #"SEARCH";
[addressfeild setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:addressfeild];
}
-(IBAction)search:(id)sender
{
[self location:str1];
}
-(void)location:(NSString *)address
{
NSString *baseUrl =#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
NSString *url = [NSString stringWithFormat:#"%#location=%#&radius=10000&name=dominos&sensor=false&key=AIzaSyCczXEpxw19qAXQMEUUA98OsMaOESNSOjM",baseUrl,address];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *queryUrl = [NSURL URLWithString:url];
NSLog(#"query url%#",queryUrl);
dispatch_async(dispatch_get_main_queue(), ^{
NSData *data = [NSData dataWithContentsOfURL:queryUrl];
[self fetchData:data];
});
}
-(void)fetchData:(NSData *)data
{
NSString *data1 = [NSString stringWithUTF8String:[data bytes]];
// NSLog(#"Response data: %#", data1);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* results =[json objectForKey:#"results"];
//NSLog(#"Data is:%#" ,results);
for (int i = 0;i <[results count]; i++) {
NSDictionary *result = [results objectAtIndex:i];
// NSLog(#"Data is %#", result);
NSString *address = [result objectForKey:#"vicinity"];
// NSLog(#"Address is %#", address);
NSString *name = [result objectForKey:#"name"];
//NSLog(#"name is %#", name);
NSDictionary *geometry = [result objectForKey: #"geometry"];
NSDictionary *locations = [geometry objectForKey:#"location"];
NSString *lat =[locations objectForKey:#"lat"];
NSString *lng =[locations objectForKey:#"lng"];
//NSLog(#"longitude is %#", lng);
NSDictionary *gc = [[NSDictionary alloc]initWithObjectsAndKeys:lat,#"lat",lng,#"lng",address,#"address",name,#"name", nil];
location = gc;
double lat1 = [[location objectForKey:#"lat"] doubleValue];
NSLog(#"Marker position%f",lat1);
double lng1 = [[location objectForKey:#"lng"] doubleValue];
NSLog(#"Marker position%f",lng1);
GMSMarker *marker = [[GMSMarker alloc]init];
CLLocationCoordinate2D local = CLLocationCoordinate2DMake(lat1, lng1);
marker.position = local;
marker.title = [ location objectForKey:#"name"];
NSLog(#"Address is %#",marker.title);
marker.snippet = [location objectForKey:#"address"];
marker.map = map;
GMSCameraUpdate *cams = [GMSCameraUpdate setTarget:local zoom:12];
[map animateWithCameraUpdate:cams];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I am facing trouble with the functions which i bolded up. Actually i want to pass the co-ordinates of my current location from placevcViewController.m to fetchurl.m through a function -(void)location:(CLLocationManager *)address withCallback:(SEL)sel withDelegate: (id)delegate; , but somehow it is not working. Either the function is incorrect or i am not using the correct data type for fetching the co-ordinates.
Updates :
I have update the above code in fetchurl.m file(you can c ** there the code within the stars is upadted ) , and the updation is helping me to get the array of multiple locations. But now i am not getting how to add the marker on each location.
To use the delegate-protocol pattern successfully, you need some additional setup:
PlacevcViewController.h needs to define both a delegate property, and define the protocol:
#property (nonatomic, assign) id delegate;
//at the bottom of your file, below the #interface ... #end
#protocol nameOfYourProtocol <NSObject>
-(void)methodForDoingSomething:(SomeClass*)argument;
#end
Then within PlacevcViewController.m you can call your delegate method like this:
[self.delegate methodForDoingSomething:anArgument];
Then you assign your delegate and implement the method in the target class (fetchUrl.h in your case)
//declare conformity to the protocol like this in the header file
#interface fetchurl : NSObject <nameOfYourProtocol>
and finally in the fetchUrl.m file:
//assign the delegate to self when creating an instance of fetchUrl
fu = [[fetchUrl alloc] init];
[fu setDelegate:self];
//implement the delegate method
- (void)methodForDoingSomething:(SomeClass*)argument {
//your code goes here
}
While there is nothing right or wrong about using the delegate-protocol pattern, from what I can tell of your example a simpler approach might be to just define a method within fetchUrl that returns the items you need and let the owner of that instance of fetchUrl handle it. ie:
- (NSDictionary*)fetchData:(NSData*)data {
//do the work and create a dictionary
//return theDictionary
}
and then just consume the result in your placevcViewController:
NSDictionary* results = [fu fetchData:someData];
//now work with the results

Resources