本文介绍了MapKit - 在地图放大时使路线沿着街道走的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的应用程序,它在MapKit上的两个位置之间绘制路线。我正在使用Google Map API。我使用了我在网上找到的资源,这里是我用来向Google发送请求的代码:

  _httpClient = [AFHTTPClient clientWithBaseURL:[ NSURL URLWithString:@http://maps.googleapis.com/]]; 
[_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[_httpClient setDefaultHeader:@Acceptvalue:@application / json];

NSMutableDictionary * parameters = [[NSMutableDictionary alloc] init];
[参数setObject:[NSString stringWithFormat:@%f,%f,coordinate.latitude,coordinate.longitude] forKey:@origin];
[参数setObject:[NSString stringWithFormat:@%f,%f,endCoordinate.latitude,endCoordinate.longitude] forKey:@destination];
[参数setObject:@trueforKey:@sensor];

NSMutableURLRequest * request = [_httpClient requestWithMethod:@GETpath:@maps / api / directions / jsonparameters:parameters];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * operation,id responseObject){
NSInteger statusCode = operation.response.statusCode;

if(statusCode == 200)
{
NSLog(@Success:%@,operation.responseString);
}
else
{
NSLog(@Status code =%d,statusCode);

$ b失败:^(AFHTTPRequestOperation * operation,NSError * error){
NSLog(@Error:%@,operation.responseString);

}
];

[_httpClient enqueueHTTPRequestOperation:operation];

这完美无瑕。当我运行这个程序并尝试显示洛杉矶和芝加哥之间的路线时,以下是它的外观:



但是。当我缩放地图到街道层时,路线如下: alt =洛杉矶 - 芝加哥航线放大>



有人知道我怎么能实现这条路线,我在地图放大时绘制街道?我想要通过街道展示确切的路线。我不知道是否需要在Google向我的请求中添加其他参数。



任何帮助或建议都会很棒。非常感谢!






[edit#1:添加来自Google的请求网址和响应]



从上面的代码创建操作对象后,我的请求URL如下所示:

  http://maps.googleapis.com/maps/api/directions/json?sensor=true&destination=34%2E052360,-118%2E243560&origin=41%2E903630,-87%2E629790 

只需将该网址粘贴到您的浏览器中,即可看到Google发送的JSON数据代码也可以。




   - (void)parseResponse:(NSData *)response 
{
NSDictionary * dictResponse = [NSJSONSerialization JSONObjectWithData:响应选项:NSJSONReadingMutableContainers错误:无];
NSArray * routes = [dictResponse objectForKey:@routes];
NSDictionary * route = [routes lastObject];

if(route)
{
NSString * overviewPolyline = [[route objectForKey:@overview_polyline] objectForKey:@points];
_path = [self decodePolyLine:overviewPolyline]; (NSMutableString alloc)initWithCapacity:$ {

} [encodedStr length]];
[encoded appendString:encodedStr];
[编码的replaceOccurrencesOfString:@\\\withString:@\\
选项:NSLiteralSearch
范围:NSMakeRange(0,[编码长度]) ]。
NSInteger len = [编码长度];
NSInteger index = 0;
NSMutableArray * array = [[NSMutableArray alloc] init];
NSInteger lat = 0;
NSInteger lng = 0;

while(index< len)
{
NSInteger b;
NSInteger shift = 0;
NSInteger结果= 0;

do
{
b = [encoded characterAtIndex:index ++] - 63;
result | =(b& 0x1f)<<转移;
shift + = 5;
} while(b> = 0x20);

NSInteger dlat =((result& 1)?〜(result>> 1):(result>> 1));
lat + = dlat;
shift = 0;
结果= 0;

do
{
b = [encoded characterAtIndex:index ++] - 63;
result | =(b& 0x1f)<<转移;
shift + = 5;
} while(b> = 0x20);

NSInteger dlng =((result& 1)?〜(result>> 1):(result>> 1));
lng + = dlng;
NSNumber * latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
NSNumber * longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];

CLLocation * location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[array addObject:location];
}

返回数组;
}


解决方案

给你所有的观点,或者你没有看到所有的观点。实际上,我希望地标之间的多段线不仅仅是你的地标(用直线)。

看看您是否有限
  • 提供Google发回的json数据。 >我不太确定他们使用的是与Google使用的完全不同的墨卡托投影。


    I wrote simple application which draws route between two locations on MapKit. I am using Google Map API. I used resources I found online and here's the code I am using to make request to Google:

    _httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://maps.googleapis.com/"]];
        [_httpClient registerHTTPOperationClass: [AFJSONRequestOperation class]];
        [_httpClient setDefaultHeader:@"Accept" value:@"application/json"];
    
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
        [parameters setObject:[NSString stringWithFormat:@"%f,%f", coordinate.latitude, coordinate.longitude] forKey:@"origin"];
        [parameters setObject:[NSString stringWithFormat:@"%f,%f", endCoordinate.latitude, endCoordinate.longitude] forKey:@"destination"];
        [parameters setObject:@"true" forKey:@"sensor"];
    
        NSMutableURLRequest *request = [_httpClient requestWithMethod:@"GET" path: @"maps/api/directions/json" parameters:parameters];
        request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];    
        [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
            NSInteger statusCode = operation.response.statusCode;
    
            if (statusCode == 200)
            {
                NSLog(@"Success: %@", operation.responseString);
            }
            else
            {
                NSLog(@"Status code = %d", statusCode);
            }
        }
                                          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                              NSLog(@"Error: %@",  operation.responseString);
    
                                          }
         ];
    
        [_httpClient enqueueHTTPRequestOperation:operation];
    

    This works flawlessly. When I run this and try to show route between LA and Chicago, here's how it looks like:

    BUT. When I zoom map to street level, here's how route looks like:

    Does anyone know how can I achieve that route I am drawing follows streets when map is zoomed? I'd like route to show exact path through the streets. I don't know if some additional parameter needs to be added to my request to Google.

    Any help or advice would be great. Many thanks in advance!


    [edit #1: Adding request URL and response from Google]

    My request URL after creating operation object from code above looks like this:

    http://maps.googleapis.com/maps/api/directions/json?sensor=true&destination=34%2E052360,-118%2E243560&origin=41%2E903630,-87%2E629790
    

    Just paste that URL to your browser and you will see the JSON data Google sends as the response which I get in my code also.


    [edit #2: Parsing answer from Google and building the path]

    - (void)parseResponse:(NSData *)response
    {
        NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
        NSArray *routes = [dictResponse objectForKey:@"routes"];
        NSDictionary *route = [routes lastObject];
    
        if (route)
        {
            NSString *overviewPolyline = [[route objectForKey: @"overview_polyline"] objectForKey:@"points"];
            _path = [self decodePolyLine:overviewPolyline];
        }
    }
    
    - (NSMutableArray *)decodePolyLine:(NSString *)encodedStr
    {
        NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
        [encoded appendString:encodedStr];
        [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                    options:NSLiteralSearch
                                      range:NSMakeRange(0, [encoded length])];
        NSInteger len = [encoded length];
        NSInteger index = 0;
        NSMutableArray *array = [[NSMutableArray alloc] init];
        NSInteger lat=0;
        NSInteger lng=0;
    
        while (index < len)
        {
            NSInteger b;
            NSInteger shift = 0;
            NSInteger result = 0;
    
            do
            {
                b = [encoded characterAtIndex:index++] - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
    
            NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
    
            do
            {
                b = [encoded characterAtIndex:index++] - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
    
            NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
            lng += dlng;
            NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
            NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
    
            CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
            [array addObject:location];
        }
    
        return array;
    }
    
    解决方案

    It looks like Google is not giving you all the points, or you are not looking at all the points. Actually, I'd expect polylines between placemarks, not only placemarks like you seem to have (with a straight line).

    • Check DirectionsStatus in the response to see if you are limited
    • Provide the json data that Google sends back.

    I'm not so sure they use a radically different Mercator projection from the one used by Google.

    这篇关于MapKit - 在地图放大时使路线沿着街道走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 10-30 01:59