如何使用UISearchBar搜索MKMapView?

2020/12/16 03:31 · ios ·  · 0评论

我有一个需要具有类似搜索功能的应用程序,例如Apple“地图”应用程序(包括在iPhone,iPod Touch和iPad中)。

所涉及的功能应该不是一件容易的事,但是对于如何在搜索栏中输入街道地址,然后获取该地址的坐标或可以帮助我实际移动地图和在那个地方的中心。

我的意思是,我必须查询什么,Apple是否提供“地址搜索API方法”?还是我需要直接使用google maps API?

我很想听听应该怎么做。

这也许是最简单的方法。它使用Apple服务器进行地理编码。有时,苹果服务器比Google提供更好的响应。很快(在IOS 6.1中),谷歌地图将完全脱离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];
    }];
}

好吧,回答我自己的问题:

如前所述,最好的方法是使用Google Maps API,它支持多种格式,但是由于多种原因,我选择了JSON。

因此,这里是执行对Google Maps的JSON查询并获取查询坐标的步骤。请注意,并非所有正确的验证都已完成,这仅是概念证明。

1)下载一个适用于iPhone的JSON框架/库,我选择了其中的一个,它非常好,并且似乎是一个活跃的项目,另外还有一些商业应用程序正在使用它。因此,将其添加到您的项目中(此处说明)。

2)要查询Google Maps的地址,我们需要建立一个这样的请求URL:http :
//maps.google.com/maps/geo?q=Paris+France

该网址将为查询“ 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 Maps发送请求:

- (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问题,将一种方法名称修改为“ searchCoordinatesForAddress:”。我不得不说,此方法可以很好地证明概念,但是如果您打算下载较大的JSON文件,则必须追加到NSMutableData对象以将所有查询保存到Google服务器。(请记住HTTP查询是分段的。)

如果您搜索区域,此链接将为您提供帮助。

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];

请注意,第二个?应该是&

Swift版本,适用于iOS 9:

let geocoder = CLGeocoder()
geocoder.geocodeAddressString(addressString) { (placemarks, error) in

    if let center = (placemarks?.first?.region as? CLCircularRegion)?.center {

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpanMake(0.02, 0.02))
        self.mapView.setRegion(region, animated: true)
    }
}

基于user1466453的答案。

如果其他任何人遇到相同的问题,请点击以下链接:https :
//github.com/stig/json-framework/
向下滚动到
Project重命名为SBJson

另外,这是在您的应用使用之前获取所有数据的代码。请注意委托方法“已接收数据”,因为该方法将可变数据对象与下载的数据附加在一起。

我只使用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];
}

//步骤一//这很重要,因为它一收到响应就创建了可变数据对象

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

}

///步骤二//这很重要,因为它会在数据对象中附加数据

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

//第三步...... //现在,您已经拥有了所有数据

- (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
}

您可以使用Google的API服务从文本搜索字符串中获取经/纬度坐标。确保传递用户的当前位置,以便相关的结果。阅读以下问题的答案:在MKMapView上搜索和显示营业地点

本文地址:http://ios.askforanswer.com/ruheshiyonguisearchbarsousuomkmapview.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!