MapView only shows correct location after 2nd load - iphone

Im struggling with a mapview on my app. When loading the screen with the mapview on, the map just opens to the default location for mapviews. However, when I return to the previous scren and then launch the map for a 2nd time, the correct location is displayed.
Obviously, this isn't ideal.
Any suggestions please?
My code is:
CLLocation *mapLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[[self map] setCenterCoordinate:[mapLocation coordinate]];
[[self map] setRegion: MKCoordinateRegionMakeWithDistance([mapLocation coordinate], 1000, 1000)];
MapAnnotation *annotation = [[MapAnnotation alloc] init];
[annotation setCoordinate:[mapLocation coordinate]];
[[self map] addAnnotation:annotation];
Thank you!

I set the current location like this:
Location.h:
#interface WhereamiViewController : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate> {
CLLocationManager *locationManager;
MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
IBOutlet UITextField *locationTextField;
}
- (void)findLocation;
- (void)foundLocation:(CLLocation *)loc;
- (IBAction)setMapTyp:(id)sender;
#property MKMapType mapType;
#property (nonatomic, retain) IBOutlet MKMapView *worldView;
#property (nonatomic, readonly) NSDate *currentDate;
#end
Location.m:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(#"%#", newLocation);
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if (t < -180) {
return;
}
[self foundLocation:newLocation];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(#"Could not find location: %#", error);
}
- (void)findLocation {
[locationManager startUpdatingLocation];
[activityIndicator startAnimating];
[locationTextField setHidden:YES];
}
- (void)foundLocation:(CLLocation *)loc {
CLLocationCoordinate2D coord = [loc coordinate];
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"HH:mm, dd. MMM. yyyy "];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
MyOwnMapPoint *mp = [[MyOwnMapPoint alloc] initWithCoordinate:coord
title:[locationTextField text]
subtitle:dateString];
NSLog(#"Die Uhrzeit ist: %#", dateString);
[worldView addAnnotation:mp];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 250, 250);
[worldView setRegion:region animated:YES];
//Reset the UI
[locationTextField setText:#""];
[activityIndicator stopAnimating];
[locationTextField setHidden:NO];
[locationManager stopUpdatingLocation];
}
Hope its giving you an idea!

Related

how to get current location in google map sdk in iphone

I want to set camera on current location and zoom level upto 10.
So I have written code like this and for current location i get hint from this post.
How to use delegates in Google map API for IOS 6
here is my code
mapView_=[[GMSMapView alloc]initWithFrame:CGRectZero];
CLLocationCoordinate2D currentPosition = mapView_.myLocation.coordinate;
GMSCameraPosition* camera =
[GMSCameraPosition cameraWithTarget: currentPosition zoom: 10];
mapView_.camera = camera;
mapView_.delegate=self;
mapView_.mapType = kGMSTypeSatellite;
mapView_.myLocationEnabled = YES;
self.view = mapView_;
mapView_.settings.myLocationButton = YES;
But coordinate is 0.00 in device.
Please Any Can help to solve out this issue?
Try this:
#property (nonatomic, retain) IBOutlet GMSMapView *googleMapView;
#property (nonatomic, retain) CLLocationManager *locationManager;
- (void)showCurrentLocation {
_googleMapView.myLocationEnabled = YES;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:newLocation.coordinate.latitude
longitude:newLocation.coordinate.longitude
zoom:17.0];
[_googleMapView animateToCameraPosition:camera];
//...
}
You can add an observer for the myLocation property as follows:
[self.mapView addObserver:self
forKeyPath:#"myLocation"
options:(NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld)
context:NULL];
You should then implement the following method:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:#"myLocation"]) {
NSLog(#"My position changed");
}
}
write this line in info plist
CLLocationManager requestAlwaysAuthorization (string) abcd
//code and also set annotation pin
.h
#import<MapKit/Mapkit.h>
CLLocationManager *locationManager;
#property(nonatomic, weak) IBOutlet MKMapView* mapView;
#property(nonatomic,retain)CLLocationManager* locationManager;
- (id)init {
self = [super init];
if(self != nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
}
return self;
}
in viewDidLoad
_mapView.showsUserLocation = YES;
_mapView.mapType = MKMapTypeStandard;
_mapView.delegate = self;
if(IS_OS_8_OR_LATER) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
// NSDictionary *dictlatitude = [_dict objectForKey:#"latitude"];
float strlatitude = [[_dict objectForKey:#"latitude"] floatValue];
// NSDictionary *dictlongitude = [_dict objectForKey:#"longitude"];
float strlongitude = [[_dict objectForKey:#"longitude"] floatValue];
NSLog(#"Staring Point latitude : %f", strlatitude);
NSLog(#"Staring Point longitude: %f", strlongitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
CLLocationCoordinate2D location;
location.latitude = strlatitude;
location.longitude = strlongitude;
region.span = span;
region.center = location;
[_mapView setRegion:region animated:YES];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title=#"name of the pin";
ann.coordinate = region.center;
[_mapView addAnnotation:ann];

How to get user's location in a later screen for the MapKit?

I am building a navigation-based app for the iPhone, where I calculate the user's geolocation in the RootViewController (this is the code for my RootViewController.h) class:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "SecondViewController.h"
#import <sqlite3.h>
#interface RootViewController : UITableViewController <CLLocationManagerDelegate>{
SecondViewController *secondViewController;
NSUInteger numUpdates;
CLLocationManager *lm;
CLLocation *firstLocation;
CLLocation *secondLocation;
}
#property (nonatomic, retain) SecondViewController *secondViewController;
#property (nonatomic, retain) NSMutableArray *restaurants;
#property (nonatomic, retain) NSArray *sortedRestaurants;
here is the code for my RootViewController.m class:
- (void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D location;
NSString *lat = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.latitude];
double lat1 = newLocation.coordinate.latitude;
location.latitude = newLocation.coordinate.latitude; //setting the latitude property of the location variable
NSString *lng = [[NSString alloc] initWithFormat:#"%g", newLocation.coordinate.longitude];
double lon1 = newLocation.coordinate.longitude;
location.longitude = newLocation.coordinate.longitude; //setting the longitude property of the location variable
MapViewController *mController = [[MapViewController alloc] initWithNibName:#"MapViewController" bundle:[NSBundle mainBundle]];
self.mapViewController = mController;
[mController release];
self.mapViewController.userCoord = [[[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude] autorelease];
//in the above line I get the error, "incompatible type for argument 1 of 'setUserCoord' "
[lm stopUpdatingLocation];
Because I am calculating the user's geolocation in the RootViewController class, I would like to re-use these value when I use the MapKit later on in the application in the MapViewController.m class:
- (void)viewDidLoad {
[super viewDidLoad];
MKCoordinateRegion region;
MKCoordinateSpan span;
region.center = userCoord;
/* userCoord is declared as an object of type CLLocationCoordinate2D
in MapViewController.h, and is declared as a property, and then
synthesized in the .m class. Even though I am trying to center
the map on the user's coordinates, the map is neither centering,
nor zooming to my settings. */
span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
region.span = span;
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
[mapView setRegion:region animated:YES];
RestaurantAnnotation *rAnnotation = [[RestaurantAnnotation alloc] init];
rAnnotation.title = restaurantObj.name;
rAnnotation.subTitle = restaurantObj.address;
CLLocationCoordinate2D newCoord = {restaurantObj.latitude, restaurantObj.longitude};
rAnnotation.coordinate = newCoord;
[mapView addAnnotation:rAnnotation];
}
I would like the map to be centered on the user's location, and choose appropriate span values as well.
There are a lot of ways to do this, the way I've done it is to store the location in NSUserDefaults and access that value later when I'm presenting my map. The benefit of doing it this way is that the user's location persists between runs, so if the next time they open the app they're having trouble getting a GPS signal, you still have a location to display.
This code may not be 100%, i'm writing it from memory:
#define latKey #"latKey"
#define lonKey #"lonKey"
#define locationKey #"locationKey"
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSNumber *lat = [NSNumber numberWithDouble:newLocation.coordinate.latitude];
NSNumber *lon = [NSNumber numberWithDouble:newLocation.coordinate.longitude];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:lat, latKey, lon, lonKey, nil];
[[NSUserDefaults standardUserDefaults] addObjectForKey:locationKey];
}
- (void)viewDidLoad {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictForKey:locationKey];
CLLocation *location = [[CLLocation alloc] initWithLatitude:[[dict objectForKey:lat] doubleValue] longitude:[[dict objectForKey:lon] doubleValue]];
}

Need to get current location and destination location pin

How do I get the current location with green pin and destination location with red pin?
When I work on some stuff I get only destination location with red pin, not at the current location.
My source code.
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import <CoreLocation/CoreLocation.h>
#interface AddressAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
// CLLocationManager *locationManager;
// CLLocation *currentLocation;
}
#end
#interface MapViewController : UIViewController <CLLocationManagerDelegate,MKMapViewDelegate> {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
NSString *address;
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
#property(nonatomic,retain)CLLocation *currentLocation;
#property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
#end
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return #"Event";
}
- (NSString *)title{
//return #"Title";
return #"Allure-Exclusive";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES;
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title=#"Map-View";
// [self addressLocation];
[self showAddress];
NSLog(#"address is %#",address);
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.5;
span.longitudeDelta=0.5;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(#"locationString %#",locationString);
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
NSLog(#"listItems %#",[listItems objectAtIndex:2]);
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation) {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
//
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// [self stop];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[super dealloc];
}
#end
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation)
{
mapView.userLocation.title=#"Current Location";
[mapView setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
return nil;
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
}
When I changed the method. it's pointing blue and blinking,but it was pointing at different location, which is at infinite Loop mariani Ave location.
It was running this in a simulator.
You'll want to set showsUserLocation.
mapView.showsUserLocation = YES;

need to drop pin at two places... current location and events locations

I need help on this .... drop the pins.
current location.... pin drop.... with blue....
Event location :locations latitude:53.373812...longitude 4.890951 with red pin.
I did like this:
#interface AddressAnnotation : NSObject<MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
// CLLocationManager *locationManager;
// CLLocation *currentLocation;
}
#end
#interface MapViewController : UIViewController <CLLocationManagerDelegate> {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
NSString *address;
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
+(MapViewController *)sharedInstance;
-(void)start;
-(void)stop;
-(BOOL)locationKnown;
#property(nonatomic,retain)CLLocation *currentLocation;
#property(nonatomic,retain)NSString *address;
-(CLLocationCoordinate2D) addressLocation;
-(void)showAddress;
#end
//Implementation file.
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return #"Event";
}
- (NSString *)title{
//return #"Title";
return #"Location ";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
//NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
[locationManager startUpdatingLocation];
}
-(void)stop{
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.title=#"Map-View";
[self addressLocation];
[self showAddress];
NSLog(#"address is %#",address);
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[super dealloc];
}
#end
Please help me out...
thanks in adavance.
Showing user current location is simple.
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES; //This will show the current location as blue dot in your mapview
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
In your viewForAnnotation Delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if (annotation == mapView.userLocation)
{
// This code will execute when the current location is called.
return nil;
}
else
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}

Obtain user location from a MKMapView

Is it possible to use the MKMapView's own location manager to return the users current location to pass into a webservice?
I have mapView.showsUserLocation=YES; and this does return a valid blue dot at my location, but in the simulator, its Cupertino - which is fine, but when i look at
mapView.userLocation.coordinate.latitude, its equal to 180, whereas a CLLocationManager returns the correct one, 37.3317.
I want to avoid having multiple location managers for my three tabs, so using the mapViews own would be helpful.
Thanks.
You can get the user location from the MKMapView. You are just missing a property in your retrieval of it. It should be:
mapView.userLocation.location.coordinate.latitude;
userLocation only stores a CLLocation location attribute and a BOOL updating attribute. You must go to the location attribute to get coordinates.
-Drew
EDIT: The MKMapView's userLocation does not update until the map has finished loading, and checking too early will return zeros. To avoid this, I suggest using the MKMapViewDelegate method
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation.
So, to use a unique CLLocateManager, you can create a class to be the delegate for all you maps., so, instead of doing:
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
Do something like:
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = mySharedDelegate;
Where mySharedDelegate is your class with all the CLLocationManager delegate methods.
You can only get a valid coordinate for the userLocation, after the first calling of - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
When this method is called it is because the GPS has found the new location and so the blue dot will be moved to there and the userLocation will have the new coordinate.
Use the following method on your CLLocationManager delegate to log the current location when it is found:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"---------- locationManager didUpdateToLocation");
location=newLocation.coordinate;
NSLog(#"Location after calibration, user location (%f, %f)", _mapView.userLocation.coordinate.latitude, _mapView.userLocation.coordinate.longitude);
}
Have you got the idea?
Cheers,
VFN
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MyMapannotation class]])
{
MyMapannotation *annotation12=(MyMapannotation *)annotation;
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] ;
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
pinView.tag=annotation12.tag;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
rightButton.tag=annotation12.tag;
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"artpin"]];
pinView.image = profileIconView.image;
return pinView;
}
else
return nil;
}
-(IBAction)showDetails:(id)sender
{
UIButton *btn=(UIButton *)sender;
}
-(void)Load_mapview
{
for (int i=0; i<[arr_nearby count]; i++)
{
NSNumber *latitude = [[[[arr_nearby objectAtIndex:i] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"];
NSNumber *longitude = [[[[arr_nearby objectAtIndex:i] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"];
NSString *title = [[arr_nearby objectAtIndex:i] valueForKey:#"name"];
//Create coordinates from the latitude and longitude values
CLLocationCoordinate2D coord;
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
MyMapannotation *annotation = [[MyMapannotation alloc] initWithTitle:title AndCoordinate:coord andtag:i];
[_map_nearby addAnnotation:annotation];
// [annotations addObject:annotation];
}
[self zoomToLocation];
}
-(void)zoomToLocation
{
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = [[[[[arr_nearby objectAtIndex:0] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"] floatValue];
zoomLocation.longitude= [[[[[arr_nearby objectAtIndex:0] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"] floatValue];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 7.5*5,7.5*5);
[_map_nearby setRegion:viewRegion animated:YES];
[_map_nearby regionThatFits:viewRegion];
}
//
// MyMapannotation.h
// IOS_Googgle
//
// Created by Vivek Chauhan on 27/06/16.
// Copyright (c) 2016 anand. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MyMapannotation : NSObject <MKAnnotation>
#property (nonatomic,copy) NSString *title;
#property (nonatomic,assign) int tag;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton;
#end
//
// MyMapannotation.m
// IOS_Googgle
//
// Created by Vivek Chauhan on 27/06/16.
// Copyright (c) 2016 anand. All rights reserved.
//
#import "MyMapannotation.h"
#implementation MyMapannotation
#synthesize coordinate=_coordinate;
#synthesize title=_title;
#synthesize tag=_tag;
-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton
{
self = [super init];
_title = title;
_coordinate = coordinate;
_tag=tagofbutton;
return self;
}
#end