GoogleMaps iOS SDK Version 1.5 unresponsive - ios

I am using the latest GoogleMaps iOS SDK in my application and after the latest iOS update, 7.0.3, it started becoming unresponsive after first touch. Let me expand on this. After the first touch on the map, the map becomes unresponsive. At first, you can pinch zoom, drag, swipe, and everything else but after that first touch, it no longer works. This started happening after Apple updated their iOS. If I use the iOS6 simulator, I can can do all the gestures even after the first touch. I don't know if this is because of the iOS update or something is wrong with my code. If anyone has any suggestions or has gone through something like this that could guide me, that could be greatly appreciated. Thanks in advance.
Followed the website instructions here: (https://developers.google.com/maps/documentation/ios/start#adding_the_google_maps_sdk_for_ios_to_your_project)
and it works on iOS6 and was working on iOS7 before.
MapsViewController.m
#import "MapsViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface MapsViewController ()
#end
#implementation MapsViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.storeNamesArray = [[NSMutableArray alloc] init];
self.storePricesArray = [[NSMutableArray alloc] init];
self.storeLatitudeArray = [[NSMutableArray alloc] init];
self.storeLongitudeArray = [[NSMutableArray alloc] init];
self.priceTypeArray = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{ NSData *data =
[NSData dataWithContentsOfURL:[NSURL URLWithString:
[NSString stringWithFormat: #"http://www.someurl.com/mobile-api"]]];
[self performSelectorOnMainThread:#selector(fetchData:) withObject:data
waitUntilDone:YES]; });
}
-(void)fetchData:(NSData *)responseData
{
if (responseData)
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *stores =[json objectForKey:#"stores"];
for(NSDictionary *location in stores)
{
[self.storeNamesArray addObject:[location objectForKey:#"name"]];
[self.storePricesArray addObject:[location objectForKey:#"price"]];
[self.storeLatitudeArray addObject:[location objectForKey:#"latitude"]];
[self.storeLongitudeArray addObject:[location objectForKey:#"longitude"]];
[self.priceTypeArray addObject:[location objectForKey:#"price_type"]];
}
}
double lat = 0.0;
double lon = 0.0;
GMSCameraPosition *camera;
if(self.currentLocationArray.count !=0)
{
lat = [self.currentLocationArray[0] doubleValue];
lon = [self.currentLocationArray[1] doubleValue];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:12];
}
else
{
lat = [self.storeLatitudeArray[0] doubleValue];
lon = [self.storeLongitudeArray[0] doubleValue];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:9];
}
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
for(int i=0; i<self.storeNamesArray.count; i++)
{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.title = self.storeNamesArray[i];
marker.snippet = [NSString stringWithFormat:#"%# $%#", self.priceTypeArray[i], self.storePricesArray[i]];
marker.position = CLLocationCoordinate2DMake([self.storeLatitudeArray[i] doubleValue], [self.storeLongitudeArray[i] doubleValue]);
marker.map = mapView;
}
if(self.currentLocationArray.count !=0)
{
GMSMarker *currentMarker = [[GMSMarker alloc] init];
currentMarker.title = #"Current Location";
currentMarker.snippet = #"You are here";
currentMarker.position = CLLocationCoordinate2DMake(lat, lon);
currentMarker.map = mapView;
currentMarker.icon = [UIImage imageNamed:#"temp_userLocation"];
mapView.selectedMarker = currentMarker;
}
CGRect newFrame = self.view.bounds;
newFrame.size.height = frame.size.height / 2;
mapView.frame = newFrame;
mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
mapView.delegate = self;
[self.view addSubview:mapView];
}

I've published my reworked version of Chris's code on the Google Maps SDK for iOS bug.
The solution involved two changes to Chris's code:
Migrate the Google Map instantiation to viewDidLoad,
Push the network traffic from the Main (UI) thread to a background thread.

I don't know if that's the case here but I had same issue with URLWithString function appears only on iOS 7.0.3, I assume Apple has change the characters this function can use so if it returns nil this is your solution.
What I did is using this function to create the string before using it with URLWithString:
-(NSString *) URLEncodeString:(NSString *) str // New to fix 7.0.3 issue //
{
NSMutableString *tempStr = [NSMutableString stringWithString:str];
[tempStr replaceOccurrencesOfString:#" " withString:#"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
return [[NSString stringWithFormat:#"%#",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
On your case just change the line to this one:
dispatch_async(dispatch_get_main_queue(), ^{ NSData *data =
[NSData dataWithContentsOfURL:[NSURL URLWithString:[self URLEncodeString: [NSString stringWithFormat: #"http://www.someurl.com/mobile-api"]]]];
[self performSelectorOnMainThread:#selector(fetchData:) withObject:data
waitUntilDone:YES]; });
Hope that would help you too.

insert this code in viewDidLoad method
-(void)viewDidLoad
{
[super viewDidLoad];
// iOS7
if ([self.navigationController respondsToSelector:#selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
.... your codes
}

Related

Multiple marker is not showing

I want to show multiple marker on google map. There are answers based on this. But markers are not showing on the map. Although I am getting the latitude and longitude value based on the array result. What should I do?
Note: I have done some changes and the code running perfectly.
My code is:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self performRequestForRestaurantListing];
geometryDict=[[NSMutableDictionary alloc]init];
locationDict=[[NSMutableDictionary alloc]init];
NSLog(#"the value of list is %#", _service);
NSLog(#"the value of stringradius is %#", _stringRadius);
/*---location Manager Initialize-------*/
self.manager=[[CLLocationManager alloc]init];
self.manager.distanceFilter = 100;
self.manager.desiredAccuracy = kCLLocationAccuracyBest;
[self.manager requestAlwaysAuthorization];
self.manager.delegate=self;
[self.manager startUpdatingLocation];
[mapView setDelegate:self];
latitude=#"22.5726";
longitude=#"88.3639";
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude doubleValue]
longitude:[longitude doubleValue]
zoom:12];
[mapView animateToCameraPosition:camera];
[self coordinateOnMap:latitude andWithLongitude:longitude];
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude
{
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] init];
CLLocationCoordinate2D location;
for (int i=0;i<[restaurantList count];i++)
{
driverMarker = [[GMSMarker alloc] init];
latitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lat"];
longitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lng"];
location.latitude = [latitude floatValue];
location.longitude = [longitude floatValue];
driverMarker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude);
driverMarker.map = mapView;
}
driverMarker.icon=[UIImage imageNamed:#"marker"];
bounds = [bounds includingCoordinate:driverMarker.position];
driverMarker.title = #"My locations";
[driverMarker setTappable:NO];
mapView.myLocationEnabled = YES;
}
I guess your driveMarker gets deallocated by ARC immediatly after each loop.
If this really is your issue, you'll have to make sure that those markers "survive" the loop, e.g. with the following code:
#implementation MyController
#property (nonatomic) NSMutableArray *allMarkers;
- (void)viewDidLoad {
allMarkers = [[NSMutableArray alloc] init];
// ...
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude {
//...
[allMarkers removeAllObjects];
for (int i=0;i<[restaurantList count];i++) {
GMSMarker *driverMarker = [[GMSMarker alloc] init];
[allMarkers addObject:driveMarker];
// ...
}
}
#end
This will create an NSArray property to store all created markers, just to keep them in scope.

Adding a marker image to Google Maps on IOS Objective-C app

I have a map to show directions. I am able to tap on a direction to view an annotation with the instructions but what I am trying to do is add a marker to the directions coordinates. Here is the code I am currently using:
-(void) getDirectionsFromStart: (CLLocation*) start toEnd: (CLLocation*) end
{
NSString *mapDir = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false", start.coordinate.latitude, start.coordinate.longitude, end.coordinate.latitude, end.coordinate.longitude];
if ([self.directionsArray count] == 0) {
//parse the string response and then draw the points on a map
NSError *error;
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:mapDir] encoding:NSUTF8StringEncoding error:&error];
if (response == nil) {
NSLog(#"Google Maps error: %#", [error localizedDescription]);
NSLog(#"Google Maps recovery: %#", [error localizedRecoverySuggestion]);
//[self getDirectionsFromStart:nil toEnd:nil];
}
self.directionsArray = [gMapsJsonDirectionsParser parseJsonToMapDirections:response];
}
for (gMapsJourneyLeg *leg in self.directionsArray) {
#autoreleasepool {
self.directionsHeader.text = [NSString stringWithFormat:#"To %# Taking: %#", leg.end_address, leg.duration.text];
for (gMapsStep *step in leg.steps ) {
MKPolyline *polyLine = [gMapsJsonDirectionsParser polylineWithEncodedString:step.polyLine];
MKPolylineView *line = [[MKPolylineView alloc] initWithPolyline: polyLine];
line.fillColor = [UIColor blueColor];
line.strokeColor = [UIColor blueColor];
line.lineWidth = 5;
[self.mapView addOverlay:polyLine];
//[self.mapView setVisibleMapRect:polyLine.boundingMapRect];
//map point code
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = step.end_location.coordinate;
point.title = step.htmlInstructions;
[[self.mapView viewForAnnotation:point] setTag:1];
UIImage *image = [UIImage imageNamed:#"marker_red.png"];
[[self.mapView viewForAnnotation:point] setImage:image];
[self.mapView addAnnotation:point];
}
}
}
[self.tableView reloadData];
}
To be clear, the annotations and polyline are both fine it's just the marker is never shown.
Base on the code in the Google Docs for Markers:
Here is the sample code for adding markers with custom image.
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(51.5, -0.127);
GMSMarker *london = [GMSMarker markerWithPosition:position];
london.title = #"London";
london.icon = [UIImage imageNamed:#"house"];
london.map = mapView_;
May be you have not set the GMSMarker *london = [GMSMarker markerWithPosition:position]; that is why your marker is not visible.
Kindly check the marker without a custom image if it will show up, if not try adding the markerPosition property.

Google map is showing white screen in iOS when run second time?

I am displaying the google map using Google Maps SDK for iOS. When I start the view controller first time it shows the map fine. But when I goto the view controller second time it does not display the google map. It shows the blank screen. Actually I am passing the address in the google geo coding api from there I am getting the lang & lat then I am displaying the google map.
Code for displaying google map
//
// GmapViewController.m
// MyDex
// Created by Admin on 8/18/15.
// Copyright (c) 2015 com.vastedge. All rights reserved.
#import "GmapViewController.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import GoogleMaps;
#interface GmapViewController ()
#end
#implementation GmapViewController
{
GMSMapView *mapView_;
NSString *lat;
NSString *lng;
CLLocationDegrees latitude;
CLLocationDegrees longitude;
UIActivityIndicatorView *activityView;
}
-(void)geoCodeAddress
{
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#":/,."];
self.address = [[self.address componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSString *urlString=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#",self.address];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:urlString]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager GET:urlString parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSArray * results = [responseObject objectForKey:#"results"];
NSDictionary *records=[results objectAtIndex:0];
NSDictionary *geometry=[records objectForKey:#"geometry"];
NSLog(#"geomatry is %#",geometry);
NSDictionary *latLong=[geometry objectForKey:#"location"];
lat=[latLong objectForKey:#"lat"];
lng=[latLong objectForKey:#"lng"];
latitude=[lat floatValue];
longitude=[lng floatValue];
NSLog(#"main lat is %f",latitude);
NSLog(#"main lng is %f",longitude);
[self activityIndicator:#"hide"];
[self Loadgmap];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"failure string is");
[self activityIndicator:#"hide"];
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Warning" message:#"Unable to display map" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}];
[operation start];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self activityIndicator:#"show"];
[self geoCodeAddress];
}
-(void)Loadgmap
{
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
longitude:151.2086
zoom:6];
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = camera.target;
marker.snippet = #"Hello World";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = mapView;
self.view = mapView;
}
-(void)activityIndicator:(NSString *)show
{
if([show isEqual:#"show"])
{
NSLog(#"loading shown");
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.layer.backgroundColor = [[UIColor colorWithWhite:0.0f alpha:0.5f] CGColor];
activityView.hidesWhenStopped = YES;
activityView.frame = self.view.bounds;
[self.view addSubview:activityView];
[activityView startAnimating];
}
else
{
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
[activityView stopAnimating];
[activityView removeFromSuperview];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
Using dispatch_async(dispatch_get_main_queue(), ^{}) is a better practice, but the main problem of your white screen issue is the view in your ViewController get assigned to new value twice.
When the [self Loadgmap] is called in you viewDidLoad(), the self.view = mapView; is called. When your networking required is done, your [self Loadgmap] is called again, and the self.view = mapView; is called again, which make your view become a white screen.
You should only assign value to your view in the viewDidLoad() method, not later in other method calls.
To fix your problem, you can make a new method call -(void)updateMap():
-(void)updateMap {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[lat floatValue]
longitude:[lng floatValue]
zoom:6];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = camera.target;
marker.snippet = #"Hello World";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = (GMSMapView*)self.view;
[((GMSMapView*)self.view) animateToCameraPosition:camera];
}
You should call it inside your network request success block:
NSArray * results = [responseObject objectForKey:#"results"];
NSDictionary *records=[results objectAtIndex:0];
NSDictionary *geometry=[records objectForKey:#"geometry"];
NSLog(#"geomatry is %#",geometry);
NSDictionary *latLong=[geometry objectForKey:#"location"];
lat=[latLong objectForKey:#"lat"];
lng=[latLong objectForKey:#"lng"];
latitude=[lat floatValue];
longitude=[lng floatValue];
NSLog(#"main lat is %f",latitude);
NSLog(#"main lng is %f",longitude);
dispatch_async(dispatch_get_main_queue(), ^{
[self activityIndicator:#"hide"];
[self updateMap];
});
Your viewDidLoad() should call [self Loadgmap] first to initialize a Google Map to your view.
- (void)viewDidLoad
{
[super viewDidLoad];
[self activityIndicator:#"show"];
[self Loadgmap];
[self geoCodeAddress];
}
Full code snippet: https://gist.github.com/ziyang0621/f66dd536382b1b16597d

Google Maps SDK for IOS markers are being overwritten

I am having problems plotting multiple markers with Google Maps SDK for iOS (ver. 1.5.0). I am new to objective c (using Xcode ver 4.6.3) and the Google Maps SDK so I may be missing something obvious. Also I'm using iOS 6.1 simulator. I'm trying to learn by doing.
I have spent several days searching and have found several threads that have dealt with this topic, but none of the solutions work for me. The problem that I'm having is that my markers are overwriting each other. I created an NSArray, locations, that will have 4 columns and unknown rows. The columns are latitude, longitude, name, address.
for(int i=0;i<[locations count];i++){
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:40.0823
longitude:-74.2234
zoom:7];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView_;
mapView_.myLocationEnabled = YES;
mapView_.mapType = kGMSTypeHybrid;
mapView_.settings.myLocationButton = YES;
mapView_.settings.zoomGestures = YES;
mapView_.settings.tiltGestures = NO;
mapView_.settings.rotateGestures = NO;
NSString *lat = [[locations objectAtIndex:i] objectAtIndex:0];
NSString *lon = [[locations objectAtIndex:i] objectAtIndex:1];
double lt=[lat doubleValue];
double ln=[lon doubleValue];
NSString *name = [[locations objectAtIndex:i] objectAtIndex:2];
NSMutableArray *markersArray = [[NSMutableArray alloc] init];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.appearAnimation=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = [[locations objectAtIndex:i] objectAtIndex:3];
marker.map = mapView_;
[markersArray addObject:marker];
}
I see something wrong that's possibly related. You're overwriting markersArray every time you iterate through the locations array in the for loop. Instantiate markersArray outside of the for loop.
Could you try to NSLog the coordinates of each marker you're trying to plot?
If the coordinates are the same, the marker should plot right on top of each other making it appear that markers are being overridden, but they're just on top of each other.
Log the count of the locations and markersArray after you're done to make sure they're equal to each as a quick check.
*Edit: I see your problem. You're overriding your MapView every time you iterate through your for loop.
Try something like this:
// Create a markersArray property
#property (nonatomic, strong) NSMutableArray *markersArray;
// Create a GMSMapView property
#property (nonatomic, strong) GMSMapView *mapView_;
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupMapView];
[self plotMarkers];
}
// Lazy load the getter method
- (NSMutableArray *)markersArray
{
if (!_markersArray) {
_markersArray = [NSMutableArray array];
}
return _markersArray;
}
- (void)setupMapView
{
self.mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = self.mapView_;
self.mapView_.myLocationEnabled = YES;
self.mapView_.mapType = kGMSTypeHybrid;
self.mapView_.settings.myLocationButton = YES;
self.mapView_.settings.zoomGestures = YES;
self.mapView_.settings.tiltGestures = NO;
self.mapView_.settings.rotateGestures = NO;
// You also instantiate a GMSCameraPosition class, but you don't add it to your mapview
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:40.0823
longitude:-74.2234
zoom:7];
}
- (void)plotMarkers
{
// I don't know how you're creating your locations array, so I'm just pretending
// an array will be returned from this fake method
NSArray *locations = [self loadLocations];
for (int i=0; i<[locations count]; i++){
NSString *lat = [[locations objectAtIndex:i] objectAtIndex:0];
NSString *lon = [[locations objectAtIndex:i] objectAtIndex:1];
double lt=[lat doubleValue];
double ln=[lon doubleValue];
NSString *name = [[locations objectAtIndex:i] objectAtIndex:2];
// Instantiate and set the GMSMarker properties
GMSMarker *marker = [[GMSMarker alloc] init];
marker.appearAnimation=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = [[locations objectAtIndex:i] objectAtIndex:3];
marker.map = self.mapView_;
[self.markersArray addObject:marker];
}
}

Loading online data very slow difficult to PUSH

First of all I am running a Map page that just only show pins on map for every store. I was running only one pin on the map and it was fast after I put more than 25 pins it push very slow to the map page. What it is doing now at that process the app just load all data of the pin location (as I see in the target output) and then it push to the next screen. So please where would be my problem?
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"";
self.navigationItem.title = #"Mek";
response = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://kalkatawi.com/mapLocation.php"]];
if(response!=nil) {
NSError *parseError = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&parseError];
jsonArray1 = [[NSMutableArray alloc] init];
jsonArray2 = [[NSMutableArray alloc] init];
jsonArray3 = [[NSMutableArray alloc] init];
for(int i=0;i<[jsonArray count];i++)
{
name = [[jsonArray objectAtIndex:i] objectForKey:#"name"];
longitude = [[jsonArray objectAtIndex:i] objectForKey:#"longitude"];
latitude = [[jsonArray objectAtIndex:i] objectForKey:#"latitude"];
[jsonArray1 addObject:name];
[jsonArray2 addObject:longitude];
[jsonArray3 addObject:latitude];
self.locationMap.delegate = self; //set delegate before adding annotations
CLLocationCoordinate2D annotationCoord;
for (int i=0; i < [jsonArray count]; i++)
{
NSDictionary *annotationDictionary = [jsonArray objectAtIndex:i];
name = [annotationDictionary objectForKey:#"name"];
annotationCoord.latitude
= [[annotationDictionary objectForKey:#"longitude"] doubleValue];
annotationCoord.longitude
= [[annotationDictionary objectForKey:#"latitude"] doubleValue];
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = name;
annotationPoint.subtitle = [NSString stringWithFormat:#"%f %f", annotationPoint.coordinate.latitude, annotationPoint.coordinate.longitude];
[self.locationMap addAnnotation:annotationPoint];
//------------------------//
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(annotationPoint.coordinate, 50000, 50000);
[self.locationMap setRegion:[self.locationMap regionThatFits:region] animated:YES];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
lat = locationManager.location.coordinate.latitude;
lon = locationManager.location.coordinate.longitude;
}
}
}
else {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"You are not connected to internet" message:#"Please check the internet connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *pinView = nil;
if(annotation != locationMap.userLocation)
{
static NSString *defaultPinID = #"myPin";
pinView = (MKAnnotationView *)[locationMap dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.image = [UIImage imageNamed:#"pinpinpin.png"];
pinView.canShowCallout = YES;
pinView.enabled = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = infoButton;
}
return pinView;
}
SImple way is load data in background thread, and then when data is fully load display it on the map. You can do this in any of view controller, means you can do it in parent view controller and when you got response then update on map view controller.
Or on view did load method load data in background and update it when its load. This approach will not hold your UI. You can use blocks like this
dispatch_async(queue, ^{
//load data from server
dispatch_async(dispatch_get_main_queue(), ^{
//Update map
});
});

Resources