I'm working on the project in which i added a button on pressing it should take me to my current location on map and should show the blue indicator to indicate the location,here is the code:
-(IBAction)gotoLocation
{
if(curntloc)
{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.0112872;
mapRegion.span.longitudeDelta = 0.0112872;
[self.mapView setRegion:mapRegion animated: YES];
}
else
{
curntloc = [[CLLocation alloc] initWithLatitude:21.192415 longitude:72.821159];
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.0112872;
mapRegion.span.longitudeDelta = 0.0112872;
[self.mapView setRegion:mapRegion animated: YES];
}
}
This works fine on simulator you can see it in image,
but when i try to test it on iPhone it's getting crashed.what may be the possible reasons can any one point out? thanks
First of all i want to tell you that from simulator you can't get current location. in your code you just used a static lat. long. and for the device i share a link just check.
http://pastebin.com/Vv1wvyBh
which may be helpful to you :)
Thanks.
So I have found that with the iPhone it is a refresh issue for most of the MKMapView problems. I would suggest either resetting some properties of the map, recreating the map, or making sure that showing the user's location in the map_view is set. Resetting the properties of the map usually include something like location = map.centerCoordinate, map setCenter:location. Umm other then that I think that it could possibly be a memory issue? Something like an annotation being released at a wrong time or maybe the map itself is released?
Related
I am displaying current location for iPad in map view for this i am using following code
if ([CLLocationManager locationServicesEnabled])
{
lm = [[CLLocationManager alloc] init];
lm.delegate = self;
lm.desiredAccuracy = kCLLocationAccuracyBest;
lm.distanceFilter = 100.0f;
[lm startUpdatingLocation];
}
and i am calculating lat and longitude and passing it the url as
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps?z=15&daddr=%##%#,%#&saddr=%##%#,%#",n,lat_New,lng_New,currentLocation,currentLatt,currentLong];
I am not getting the correct direction for initial starting point and ending point for iPad in map view.
Is there anything alternative for showing correct initial and staring point in iPad map view?
Does app store rejects apps for such problems and Pleas suggest me some good alternative for this.
There are couple of things .One simulator cannot give you GPS locations.Secondly Usually gps coordinates returned first time may not be accurate.so try receiving location updates by implementing the delegate.
I have this code to set the map at the user's location:
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location=mapView.userLocation.coordinate;
location = mapView.userLocation.location.coordinate;
MKCoordinateRegion region;
region.span=span;
region.center=location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
Now when I do mapView.showsUserLocation=YES it shows my location at the right place (on my device, and the apple hq in the simulator) however, both times the code above puts me in the sea somewhere near africa!
Any ideas?
The latitude/longitude pair 0/0 is on the equator due south of Greenwich, England. That spot is in the Gulf of Guinea, off the West coast of Africa. If that's where your pin is getting placed, then your mapView.userLocation isn't getting set.
Probably your code here is running before MKMapKit has had a chance to get its location. What you really want to do is have your viewController adopt the MKMapKitDelegate protocol, set the .delegate property of your map view to self, and then implement the method:
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
That method will get called when the map kit locates the user, and you can use the userLocation value you get passed there to set the region on the map. Until that gets called the first time, though, the MapView is still working on locating itself, and your asking about its location is premature.
Also, your regionThatFits there at the end is a no-op. That method doesn't resize the region in place, it actually returns a resized region, for you to use however you will. So you want to set your map view's region to what that method returns. Like this:
[mapView setRegion:[mapView regionThatFits:region] animated:TRUE];
What I have done was add the following entry on info.plist:
NSLocationAlwaysUsageDescription
Got this info into this (very good) tutorial:
https://www.youtube.com/watch?v=Z272SMC9zuQ
You can choose this method..
- (void)mapView:(MKMapView *)_mapView regionDidChangeAnimated:(BOOL)animated{
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:_mapView.region.center.latitude longitude:_mapView.region.center.longitude];
CLLocationAccuracy accuracy = _mapView.userLocation.location.horizontalAccuracy;
if (accuracy) {
current_pickup_location = loc;
[_currentStreetSpinner startAnimating];
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error){
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
// NSLog(#"location %#",placemark.location);
NSLog(#"I am currently at %#",locatedAt);
_currentStreetLabel.text = locatedAt;
static_iVar = _currentStreetLabel.text;
[_currentStreetSpinner stopAnimating];
[self listDoctorsWithSpeciality_id:currentSpeciality_id
withProfessionalityId:currentProfessionality_id];
}];
}
}
I am answering this question because the answer picked did not really help me and I was having the exact same issue. didUpdateUserLocation is not very practical because it makes the app update every single time the location changes. The other issue with the above solution is that when the map loads it's still too early to ask for a location. So how do you ask for user location before the the map loads so that the zooming doesn't take you to Africa?
You need to request the location by using the location manager on the viewDidLoad. Then after that you can set the region.
SWIFT 3
//top of your class
let locManger = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//request user location
locManager.startUpdatingLocation()
//this is the code that sets the region based on the location
let span = MKCoordinateSpanMake(0.5, 0.5)
let location = CLLocationCoordinate2DMake((locManager.location?.coordinate.latitude)!, (locManager.location?.coordinate.longitude)!)
let region = MKCoordinateRegionMake(location, span)
yourMap.setRegion(region, animated: false)
//stop location updating
locManager.stopUpdatingLocation()
}
I am just looking at mapKit and decided to make a quick button to display my current location, however when I press the button my latitude/longitude always display as [0.000000] [0.000000].
The mapView is loaded as I can see the map on the simulator before I press the button. Previously I have done this by using coreLocation.framework and using CLLocationManager and asking for the device location that way. I am just curious why this way is not working correctly, would I be better doing this via CLLocationManager?
-(IBAction)findMePressed {
MKUserLocation *myLocation = [myMapView userLocation];
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
[myMapView setCenterCoordinate:coord animated:YES];
NSLog(#"findMePressed ...[%f][%f]", coord.latitude, coord.longitude);
}
EDIT: Added ...
-(IBAction)findMePressed {
MKUserLocation *myLocation = [myMapView userLocation];
CLLocationCoordinate2D coord = [[myLocation location] coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 350, 350);
[myMapView setRegion:region animated:YES];
}
-(void)viewDidLoad {
[super viewDidLoad];
[myMapView setShowsUserLocation:YES];
}
Gary.
Either the userLocation is not visible on the map (see the userLocationVisible property) or there is some problem setting up the myMapView property and it's nil (i.e. not connected in interface builder)
[...] as I can see the map on the simulator [...]
Test it on the device. By default, on the simulator, the coordinates you get back are Apple's headquarters. Cf. doc.
See this other SO question for workarounds and useful utilities : Testing CoreLocation on iPhone Simulator
For demonstration purpose, i need to simulate the user location in a Mapkit view.
It seems that it is possible with an undocumented API to place the blue dot anywhere on the map view.
Unfortunately, i don't know witch undocumented API to use ?
Any help ?
Did you set this?
mapView.showsUserLocation = YES;
Setting a specific location is a bit more difficult, but certainly do-able without undocumented APIs. See code below:
- (void)animateToSelectedPlace:(CGFloat)zoomLevel {
MKCoordinateRegion region;
region.center = [self getCoordinateFromComponents:chosenLatitude:chosenLongitude];
MKCoordinateSpan span = {zoomLevel,zoomLevel};
region.span = span;
[mapView setRegion:region animated:YES];
}
-(CLLocationCoordinate2D)getCoordinateFromComponents:(NSNumber*)latitude:(NSNumber*)longitude {
CLLocationCoordinate2D coord;
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
return coord;
}
Not sure that it is possible to set CUSTOM user location (usually people use image simulating blue user point). Though i am not 100% sure, so you have a chance to try something like this to check if it is possible to deal with userLocation as with MKAnnotation ...
CLLocationCoordinate2D c = self.mapView.userLocation.location.coordinate;
[[self.mapView userLocation] setCoordinate:c];
I'm using MapKit to display the user's location relative to pins around them. I'd like to be able to mimic the functionality that Maps provides via the crosshair button in the lower left-hand corner of the screen. I'm already aware that MapKit provides a CLLocation object with the user's location via MKUserLocation, I just wanted to seek advice on how I should keep focus on that location. My initial inclination was to use an NSTimer to center the map on that coordinate every 500ms or so.
Is there a better way to do this? Is there something built in to MapKit that I'm missing that will accomplish this?
Thanks so much,
Brendan
If you're on IOS5+ this is VERY easy. Just change the "userTrackingMode" using code such as:
[_mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
This will smoothly follow the users current location. If you drag the map it will even set the tracking mode back to MKUserTrackingModeNone which is usually the behaviour you want.
It's really simple to have the map update the user location automatically just like the google maps. Simply set showsUserLocation to YES
self.mapView.showsUserLocation = YES
...and then implement the MKMapViewDelegate to re-center the map when the location is updated.
-(void) mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
if( isTracking )
{
pendingRegionChange = YES;
[self.mapView setCenterCoordinate: userLocation.location.coordinate
animated: YES];
}
}
And to allow the user to zoom & pan without stealing the view back to the current location...
-(void) mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
if( isTracking && ! pendingRegionChange )
{
isTracking = NO;
[trackingButton setImage: [UIImage imageNamed: #"Location.png"]
forState: UIControlStateNormal];
}
pendingRegionChange = NO;
}
-(IBAction) trackingPressed
{
pendingRegionChange = YES;
isTracking = YES;
[mapView setCenterCoordinate: mapView.userLocation.coordinate
animated: YES];
[trackingButton setImage: [UIImage imageNamed: #"Location-Tracking.png"]
forState: UIControlStateNormal];
}
I think that I would actually use the CoreLocation CLLocationManager and use its delegate method locationManager:didUpdateToLocation:fromLocation:.
This way, you don't have the overhead of an NSTimer, and it only updates when there's a new location available.
You can pull the longitude and latitude from the CLLocation object sent to the locationManager:didUpdateToLocation:fromLocation: method and pass it to the map view.
I go with Jacob Relkin's answer. This tutorial provides a step-by-step procedure of using CoreLocation in an iPhone app. Hope this helps you.
All the Best.