簡體   English   中英

從地址獲取緯度/經度

[英]Get latitude/longitude from address

如何使用iPhone SDK 3.x從用戶輸入的完整地址(街道,城市等)獲取緯度和經度?

這是一個更新,更緊湊的unforgiven代碼版本,它使用最新的v3 API:

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    double latitude = 0, longitude = 0;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result) {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    return center;
}

它假設“位置”的坐標首先出現,例如在“視口”的坐標之前,因為它只取得它在“lng”和“lat”鍵下找到的第一個坐標。 如果您擔心這里使用的簡單掃描技術,請隨意使用合適的JSON掃描儀(例如SBJSON)。

您可以使用谷歌地理編碼 它就像通過HTTP獲取數據並解析它一樣簡單(它可以返回JSON KML,XML,CSV)。

以下是從Google獲取經緯度的類似解決方案。 注意:此示例使用SBJson庫,您可以在github上找到它:

+ (CLLocationCoordinate2D) geoCodeUsingAddress: (NSString *) address
{
    CLLocationCoordinate2D myLocation; 

// -- modified from the stackoverflow page - we use the SBJson parser instead of the string scanner --

        NSString       *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        NSString            *req = [NSString stringWithFormat: @"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];

    NSDictionary    *resultsDict = [googleResponse valueForKey:  @"results"];   // get the results dictionary
    NSDictionary   *geometryDict = [   resultsDict valueForKey: @"geometry"];   // geometry dictionary within the  results dictionary
    NSDictionary   *locationDict = [  geometryDict valueForKey: @"location"];   // location dictionary within the geometry dictionary

// -- you should be able to strip the latitude & longitude from google's location information (while understanding what the json parser returns) --

    DLog (@"-- returning latitude & longitude from google --");

    NSArray *latArray = [locationDict valueForKey: @"lat"]; NSString *latString = [latArray lastObject];     // (one element) array entries provided by the json parser
    NSArray *lngArray = [locationDict valueForKey: @"lng"]; NSString *lngString = [lngArray lastObject];     // (one element) array entries provided by the json parser

     myLocation.latitude = [latString doubleValue];     // the json parser uses NSArrays which don't support "doubleValue"
    myLocation.longitude = [lngString doubleValue];

    return myLocation;
}

使用iOS JSON更新版本:

- (CLLocationCoordinate2D)getLocation:(NSString *)address {

    CLLocationCoordinate2D center;
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSData *responseData = [[NSData alloc] initWithContentsOfURL:
                        [NSURL URLWithString:req]];    NSError *error;
    NSMutableDictionary *responseDictionary = [NSJSONSerialization
                                               JSONObjectWithData:responseData
                                               options:nil
                                               error:&error];
    if( error )
    {
        NSLog(@"%@", [error localizedDescription]);
        center.latitude = 0;
        center.longitude = 0;
        return center;
    }
    else {
        NSArray *results = (NSArray *) responseDictionary[@"results"];
        NSDictionary *firstItem = (NSDictionary *) [results objectAtIndex:0];
        NSDictionary *geometry = (NSDictionary *) [firstItem objectForKey:@"geometry"];
        NSDictionary *location = (NSDictionary *) [geometry objectForKey:@"location"];
        NSNumber *lat = (NSNumber *) [location objectForKey:@"lat"];
        NSNumber *lng = (NSNumber *) [location objectForKey:@"lng"];

        center.latitude = [lat doubleValue];
        center.longitude = [lng doubleValue];
        return center;
    }
}

您要求的是以下方法。 您需要插入Google地圖密鑰才能正常使用。

- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{

    int code = -1;
    int accuracy = -1;
    float latitude = 0.0f;
    float longitude = 0.0f;
    CLLocationCoordinate2D center;

    // setup maps api key
    NSString * MAPS_API_KEY = @"YOUR GOOGLE MAPS KEY HERE";

    NSString *escaped_address =  [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    // Contact Google and make a geocoding request
    NSString *requestString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv&oe=utf8&key=%@&sensor=false&gl=it", escaped_address, MAPS_API_KEY];
    NSURL *url = [NSURL URLWithString:requestString];

    NSString *result = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error:NULL];
        if(result){
            // we got a result from the server, now parse it
            NSScanner *scanner = [NSScanner scannerWithString:result];
            [scanner scanInt:&code];
            if(code == 200){
                // everything went off smoothly
                [scanner scanString:@"," intoString:nil];
                [scanner scanInt:&accuracy];

                //NSLog(@"Accuracy: %d", accuracy);

                [scanner scanString:@"," intoString:nil];
                [scanner scanFloat:&latitude];
                [scanner scanString:@"," intoString:nil];
                [scanner scanFloat:&longitude];


                center.latitude = latitude;
                center.longitude = longitude;

                return center;


            }
            else{
                // the server answer was not the one we expected
                UIAlertView *alert = [[[UIAlertView alloc] 
                                       initWithTitle: @"Warning" 
                                       message:@"Connection to Google Maps failed"
                                       delegate:nil
                                       cancelButtonTitle:nil 
                                       otherButtonTitles:@"OK", nil] autorelease];

                [alert show];

                center.latitude = 0.0f;
                center.longitude = 0.0f;

                return center;


            }

        }
        else{
            // no result back from the server
            UIAlertView *alert = [[[UIAlertView alloc] 
                                   initWithTitle: @"Warning" 
                                   message:@"Connection to Google Maps failed"
                                   delegate:nil
                                   cancelButtonTitle:nil 
                                   otherButtonTitles:@"OK", nil] autorelease];

            [alert show];

            center.latitude = 0.0f;
            center.longitude = 0.0f;

            return center;
        }

    }

        center.latitude = 0.0f;
        center.longitude = 0.0f;

        return center;

}

還有CoreGeoLocation,它包含了框架(Mac)或靜態庫(iPhone)中的功能。 支持通過谷歌或雅虎進行查詢,如果你有一個優先於另一個。

https://github.com/thekarladam/CoreGeoLocation

對於google地圖密鑰解決方案,如上面的unforgiven所描述的,沒有人必須免費提供應用程序? 根據Google條款和條件:9.1免費,公開訪問您的Maps API實施。 您的Maps API實施必須經常為用戶免費提供。

使用sdk 3.0中的地圖工具包,可以使用SDK輕松完成。 請參閱Apple的手冊或關注: https//developer.apple.com/documentation/mapkit

- (void)viewDidLoad
{
    app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"%@", app.str_address);


    NSLog(@"internet connect");

    NSString *Str_address=_txt_zipcode.text;

    double latitude1 = 0, longitude1 = 0;
    NSString *esc_addr =  [ Str_address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    if (result)
    {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil])
        {
            [scanner scanDouble:&latitude1];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil])
            {
                [scanner scanDouble:&longitude1];
            }
        }
    }


    //in #.hfile
   // CLLocationCoordinate2D lat;
   // CLLocationCoordinate2D lon;
   // float address_latitude;
   // float address_longitude;


    lat.latitude=latitude1;
    lon.longitude=longitude1;

    address_latitude=lat.latitude;
    address_longitude=lon.longitude;

}
func geoCodeUsingAddress(address: NSString) -> CLLocationCoordinate2D {
    var latitude: Double = 0
    var longitude: Double = 0
    let addressstr : NSString = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=\(address)" as NSString
    let urlStr  = addressstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let searchURL: NSURL = NSURL(string: urlStr! as String)!
    do {
        let newdata = try Data(contentsOf: searchURL as URL)
        if let responseDictionary = try JSONSerialization.jsonObject(with: newdata, options: []) as? NSDictionary {
            print(responseDictionary)
            let array = responseDictionary.object(forKey: "results") as! NSArray
            let dic = array[0] as! NSDictionary
            let locationDic = (dic.object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary
            latitude = locationDic.object(forKey: "lat") as! Double
            longitude = locationDic.object(forKey: "lng") as! Double
        }} catch {
    }
    var center = CLLocationCoordinate2D()
    center.latitude = latitude
    center.longitude = longitude
    return center
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM