dreamBegin dreamBegin - 4 years ago 153
Objective-C Question

how to show Custom user location programmatically

Hey I'm a beginner and learning Ios App development and i want to know that how to set the the user location programmatically like we did here using IDE (Custom Location) :-

enter image description here

I setup everything and location system is working fine in my simulator (fake location) what i have to do if i want to do the same thing programmatically i worked myself and found a little solution but its not helping me out like something is missing here's my code :-

- (IBAction)showMyLocation:(id)sender {

CLLocation *currentLocation=[[CLLocation alloc]initWithLatitude:75.14254 longitude:75.14254];


this code works but let me tell you how

  1. if i set the location in simulator to none nothing happen when i trigger the action.

  2. if i set the location to any of the given option lets just say apple it will show location of the apple and when i trigger the action the location that i give just showed for once like a second and than again the location of the apple is showed.

soo anyone who can help me out will be truly appreciated and my apologies to everyone to whom the question seem inappropriate.

Answer Source

Sometimes the location services on simulator are affected because of API key you are using. Your must have a look of this link firstly and follow the steps in order to implement google map in iOS.

Use following code to get user current location.

CLLocationManager *locationManager;
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager requestWhenInUseAuthorization];

Save latitude & longitude accordingly.

float latitude = locationManager.location.coordinate.latitude;
float longitude = locationManager.location.coordinate.longitude;

Now you can navigate user location programatically using this method

- (IBAction)showMyLocation:(id)sender {
    CLLocationCoordinate2D centre;
    centre.latitude = latitude;    // getting latitude
    centre.longitude = longitude;  // getting longitude 

    // IF USING MkMapView
    MKCoordinateRegion adjustedRegion = [mapView regionThatFits:MKCoordinateRegionMakeWithDistance(centre, 200, 200)];
    [self.mapView setRegion:adjustedRegion animated:YES];

    // IF USING GMSMapView
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
    [self.mapView animateToCameraPosition:camera];

Note: add these tow keys NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription into your project's info.plist file before see image below.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download