user1003502
user1003502

Reputation:

Show kml data? No,instead the Map is going to location (0,0)

I am using the code in this question NSURLConnection download large file (>40MB) to download a KML file and load the data in my MKMap using the KMLViewer of Apple.KML files are small <200KB so KMLViewer is just fine.The code provided in the question should be fine too exept the fact that when the I click the button (that should make the request of the url and then load the data in the map) the map just goes to location 0,0 ,zooming tremendously and so all I can see is a black map.What is going wrong? What should I do? Here is the code: (By the way, I have two connections, because one uses JSON to get Google search results for locations from a UIsearchBar.)

EDIT 1

//In the ViewController.m
-(void) searchCoordinatesForAddress:(NSString *)inAddress //for Google location search
{
NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

[urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection release];
[request release];
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0]; //webData in the header file
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if ( connection = theConnection ) //theConnection is created before
{
[webData appendData:data];
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSDictionary *results = [jsonString JSONValue];

NSArray *placemark = [results objectForKey:@"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];

NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];

[jsonString release];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];

NSString *filePath = [folder stringByAppendingPathComponent:fileName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];  

NSError *writeError = nil;

[webData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
    NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
    return;
}
NSLog(@"%@",fileURL);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.."  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];

[alert show];
[alert release];
}

-(IBAction)showKmlData:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"KMLGenerator" ofType:@"kml"];

kml = [[KMLParser parseKMLAtPath:path] retain];

NSArray *overlays = [kml overlays];
[mapview addOverlays:overlays];

NSArray *annotations = [kml points];
[mapview addAnnotations:annotations];

MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays) {
    if (MKMapRectIsNull(flyTo)) {
        flyTo = [overlay boundingMapRect];
    } else {
        flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
    }
}

for (id <MKAnnotation> annotation in annotations) {
    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
    if (MKMapRectIsNull(flyTo)) {
        flyTo = pointRect;
    } else {
        flyTo = MKMapRectUnion(flyTo, pointRect);
    }
}

mapview.visibleMapRect = flyTo;
}

EDIT 2 I have done modifications,now it doesn't go anywhere, it crashes because it doesn't find KMLGenerator.kml file (path)

-(void)showData 
{

NSString *url = /*kmlStr;*/@"http://www.ikub.al/hartav2/handlers/kmlgenerator.ashx?layerid=fc77a5e6-5985-4dd1-9309-f026d7349064&kml=1";
NSURL *path = [NSURL URLWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:path];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
theConnection = connection;
[connection release];
[request release];

}

//Search Coordinates for address entered in the searchBar
-(void) searchCoordinatesForAddress:(NSString *)inAddress
{
NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

[urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[connection release];
[request release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0]; //Here i get an alert: NSData may not respond to -setLength
                           //webData is a NSData object.
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data]; //Here i get an alert: NSData may not respond to -appendData
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if ( connection == theConnection ) //"theConnection" is for kml file download
    {
        NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *folder = [pathArr objectAtIndex:0];

        NSString *filePath = [folder stringByAppendingPathComponent:fileName];
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];  

        NSError *writeError = nil;

        [webData writeToURL: fileURL options:0 error:&writeError];

        if( writeError) {
            NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
            return;
        }

        NSLog(@"%@",fileURL);
    }
    else //it's a geocoding result
    {
        NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

        NSDictionary *results = [jsonString JSONValue];

        //check the Google geocode error code before looking for coordinates...        
        NSDictionary *statusDict = [results objectForKey:@"Status"];
        NSNumber *errorCode = [statusDict objectForKey:@"code"];
        if ([errorCode intValue] == 200)  //200 is "success"
        {
            NSArray *placemark = [results objectForKey:@"Placemark"];
            NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

            double longitude = [[coordinates objectAtIndex:0] doubleValue];
            double latitude = [[coordinates objectAtIndex:1] doubleValue];

            NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

            [self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
        }
        else
        {
            NSLog(@"geocoding error %@", errorCode);
        }

        [jsonString release];
    }
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error has occured, please verify internet connection..." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}


- (IBAction)showKmlData:(id)sender
{

NSString *path = [[NSBundle mainBundle] pathForResource:@"KMLGenerator" ofType:@"kml"];

kml = [[KMLParser parseKMLAtPath:path] retain];

NSArray *annotationsImmut = [kml points];
NSMutableArray *annotations = [annotationsImmut mutableCopy];
//[mapview addAnnotations:annotations];
[self filterAnnotations:annotations];

MKMapRect flyTo = MKMapRectNull;

for (id <MKAnnotation> annotation in annotations) {
    MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
    MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
    if (MKMapRectIsNull(flyTo)) {
        flyTo = pointRect;
    } else {
        flyTo = MKMapRectUnion(flyTo, pointRect);
    }
}

mapview.visibleMapRect = flyTo;
}   

Upvotes: 1

Views: 557

Answers (1)

user467105
user467105

Reputation:

It's still hard to pinpoint the cause but there are some problems with the code you posted.

First, in didReceiveData, this line is probably not what you want:

if ( connection = theConnection ) //theConnection is created before

The single = is doing an assignment instead of an equality check (which is ==).

Fixing that, however, is not the solution (the other problem is in connectionDidFinishLoading).

The didReceiveData method is not the right place to process your geocoding JSON result. The didReceiveData method can be called multiple times for a single url request. So it's possible that the geocoding results (just like the kml file) may be delivered in multiple chunks which cannot be processed individually in that method. The data in that method may be a partial stream of the complete result which will not make sense to process. You should only be appending the data to an NSMutableData object or, as an answer to the linked question suggests, write the data to a file.

The data can only be processed/parsed in the connectionDidFinishLoading method.

Since you are using the same connection delegate for both the kml file download and the geocoding, they both call the same connectionDidFinishLoading method. In that method, you are not checking which connection it is being called for.

When the geocoding url request finishes and calls connectionDidFinishLoading, that method takes whatever is in webData (possibly the geocoding results or empty data) and writes it to the kmlStr file. This is probably what causes the kml data to show "nothing".

You have to move the processing of the geocoding results to connectionDidFinishLoading and check there what connection is calling it.

For example:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if ( connection == theConnection ) //"theConnection" is for kml file download
    {
        NSString *fileName = [[[NSURL URLWithString:kmlStr] path] lastPathComponent];
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *folder = [pathArr objectAtIndex:0];

        NSString *filePath = [folder stringByAppendingPathComponent:fileName];
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];  

        NSError *writeError = nil;

        [webData writeToURL: fileURL options:0 error:&writeError];
        if( writeError) {
            NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError );
            return;
        }
        NSLog(@"%@",fileURL);
    }
    else //it's a geocoding result
    {
        NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];

        NSDictionary *results = [jsonString JSONValue];

        //check the Google geocode error code before looking for coordinates...        
        NSDictionary *statusDict = [results objectForKey:@"Status"];
        NSNumber *errorCode = [statusDict objectForKey:@"code"];
        if ([errorCode intValue] == 200)  //200 is "success"
        {
            NSArray *placemark = [results objectForKey:@"Placemark"];
            NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

            double longitude = [[coordinates objectAtIndex:0] doubleValue];
            double latitude = [[coordinates objectAtIndex:1] doubleValue];

            NSLog(@"Latitude - Longitude: %f %f", latitude, longitude);

            [self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];
        }
        else
        {
            NSLog(@"geocoding error %@", errorCode);
        }

        [jsonString release];
    }
}

(It's probably better to avoid using the same delegate for multiple connections. It would be cleaner to move the geocoding out to another class with its own connection object and delegate methods. By the way, iOS5 has geocoding built-in so you don't need to do this yourself. See the CLGeocoder class.)

I added a check for the Google error code. It's possible the address queried returns no results in which case there will be no placemark coordinates in which case the latitude and longitude will get set to zero. This is another possible cause of the map going to 0,0.

It also seems you are using the deprecated v2 Google geocoder. This is the latest one but you may want to switch to using CLGeocoder instead unless you need to support iOS4 or earlier.

Upvotes: 1

Related Questions