42

Apple の「マップ」アプリケーション (iPhone、iPod Touch、および iPad に付属) のような同様の検索機能が必要なアプリケーションがあります。

問題の機能を実行するのは難しいことではありませんが、検索バーに住所を入力して、その住所の座標を取得する方法や、実際に地図を移動して実際に地図を移動するのに役立つ何かを取得する方法については、まったくわかりません。その場所を中心に。

つまり、何を照会する必要があるのですか? Apple は「アドレス検索 API メソッド」を提供していますか? または、Google Maps API を直接使用する必要がありますか?

どのようにすればよいかお聞きしたいです。

4

6 に答える 6

56

これがおそらく最も簡単な方法です。ジオコーディングには Apple サーバーを使用します。Apple サーバーの方が Google よりも応答が良い場合があります。そして間もなく (IOS 6.1 で) Google マップは完全に IOS から削除されます。したがって、アプリがりんごが提供する機能内にとどまるとよいでしょう。

-(void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
    [theSearchBar resignFirstResponder];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:theSearchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
        //Error checking

        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        MKCoordinateRegion region;
        region.center.latitude = placemark.region.center.latitude;
        region.center.longitude = placemark.region.center.longitude;
        MKCoordinateSpan span;
        double radius = placemark.region.radius / 1000; // convert to km

        NSLog(@"[searchBarSearchButtonClicked] Radius is %f", radius);
        span.latitudeDelta = radius / 112.0;

        region.span = span;

        [theMapView setRegion:region animated:YES];
    }];
}
于 2012-06-19T12:47:03.757 に答える
39

わかりました、私自身の質問に答えるために:

前述したように、最善の方法は Google Maps API を使用することです。Google Maps API は多くの形式をサポートしていますが、いくつかの理由から JSON を使用することにしました。

Google マップに対して JSON クエリを実行し、クエリの座標を取得する手順は次のとおりです。すべての正しい検証が行われているわけではないことに注意してください。これは概念実証にすぎません。

1)iPhone用のJSONフレームワーク/ライブラリをダウンロードしてください。いくつかありますが、私はこれを選択しました.これは非常に優れており、アクティブなプロジェクトのようです.さらに、いくつかの商用アプリケーションがそれを使用しているようです. それをプロジェクトに追加します (手順はこちら)。

2) Google マップに住所を問い合わせるには、次のようなリクエスト URL を作成する必要があります: http://maps.google.com/maps/geo?q=Paris+France

この URL は、クエリ "Paris+France" の JSON オブジェクトを返します。

3) コード:

//Method to handle the UISearchBar "Search", 
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar 
{
    //Perform the JSON query.
    [self searchCoordinatesForAddress:[searchBar text]];

    //Hide the keyboard.
    [searchBar resignFirstResponder];
}

UISearchBar 検索を処理した後、Google マップにリクエストを送信する必要があります。

- (void) searchCoordinatesForAddress:(NSString *)inAddress
{
    //Build the string to Query Google Maps.
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

    //Replace Spaces with a '+' character.
    [urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

    //Create NSURL string from a formate URL string.
    NSURL *url = [NSURL URLWithString:urlString];

    //Setup and start an async download.
    //Note that we should test for reachability!.
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    [connection release];
    [request release];
}

もちろん、GoogleMaps サーバーの応答を処理する必要があります (注: 多くの検証が欠落しています)。

//It's called when the results of [[NSURLConnection alloc] initWithRequest:request delegate:self] come back.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{   
    //The string received from google's servers
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    //JSON Framework magic to obtain a dictionary from the jsonString.
    NSDictionary *results = [jsonString JSONValue];

    //Now we need to obtain our coordinates
    NSArray *placemark  = [results objectForKey:@"Placemark"];
    NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:@"Point.coordinates"];

    //I put my coordinates in my array.
    double longitude = [[coordinates objectAtIndex:0] doubleValue];
    double latitude = [[coordinates objectAtIndex:1] doubleValue];

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

    //I zoom my map to the area in question.
    [self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];

    [jsonString release];
}

最後に、マップをズームする機能です。これは今では些細なことです。

- (void) zoomMapAndCenterAtLatitude:(double) latitude andLongitude:(double) longitude
{
    MKCoordinateRegion region;
    region.center.latitude  = latitude;
    region.center.longitude = longitude;

    //Set Zoom level using Span
    MKCoordinateSpan span;
    span.latitudeDelta  = .005;
    span.longitudeDelta = .005;
    region.span = span;

    //Move the map and zoom
    [mapView setRegion:region animated:YES];
}

JSONの部分を理解するのは本当に面倒だったので、これが誰かに役立つことを願っています.ライブラリは私の意見ではあまり文書化されていませんが、それでも非常に優れています.

編集:

@Leo の質問により、1 つのメソッド名を「searchCoordinatesForAddress:」に変更しました。この方法は概念実証としては優れていると言わざるを得ませんが、大きな JSON ファイルをダウンロードする予定がある場合は、Google サーバーへのすべてのクエリを保持するために NSMutableData オブジェクトに追加する必要があります。(HTTP クエリはバラバラになることを覚えておいてください。)

于 2010-02-18T22:09:10.760 に答える
2

このリンクは、地域を検索する場合に役立ちます。

NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@?output=json",inAddress];

通りを検索したい場合、これはコアクトリンクです

NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=json",inAddress];

2番目はである必要があることに注意?してください&

于 2011-07-29T07:48:27.317 に答える
2

他の誰かが同じ問題を抱えている場合は、 https ://github.com/stig/json-framework/ SBJson に名前が変更されたプロジェクトまで 下にスクロールします。

また、アプリが使用する前にすべてのデータを取得するためのコードを次に示します。デリゲート メソッドの「did receive data」に注意してください。これは、可変データ オブジェクトをダウンロードしたデータに追加するためです。

MR GANDOS の searchCoodinatesMETHOD をそのまま使用しました。

- (void) searchCoordinatesForAddress:(NSString *)inAddress
{
    //Build the string to Query Google Maps.
    NSMutableString *urlString = [NSMutableString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",inAddress];

    //Replace Spaces with a '+' character.
    [urlString setString:[urlString stringByReplacingOccurrencesOfString:@" " withString:@"+"]];

    //Create NSURL string from a formate URL string.
    NSURL *url = [NSURL URLWithString:urlString];

    //Setup and start an async download.
    //Note that we should test for reachability!.
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

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

    [connection release];
    [request release];
}

// ステップ 1 // これは、応答が受信されるとすぐに可変データ オブジェクトを作成するため重要です。

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
    if (receivedGeoData) 
    {
        [receivedGeoData release];
        receivedGeoData = nil;
        receivedGeoData = [[NSMutableData alloc] init];
    }
    else
    {
        receivedGeoData = [[NSMutableData alloc] init];
    }

}

/// ステップ 2 // データにデータ オブジェクトを追加するため、これは重要です。

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

// ステップ 3...... // すべてのデータが揃ったので、それを利用します

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *jsonResult = [[NSString alloc] initWithData:receivedGeoData encoding:NSUTF8StringEncoding];
    NSError *theError = NULL;
    dictionary = [NSMutableDictionary dictionaryWithJSONString:jsonResult error:&theError];

    NSLog(@"%@",dictionary);

    int numberOfSites = [[dictionary objectForKey:@"results"] count];
    NSLog(@"count is %d ",numberOfSites);      
}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    // Handle the error properly
}
于 2011-06-23T09:41:46.157 に答える