2014-07-22 110 views
1

我正在試圖繪製多個MKPolylines對應相應的lat/lng點陣列。但是,當我添加Overlay到我的mapView時,這些點是繪製的,但沒有連接。通過JSON文本MKPolyline只能繪製點

-(void)addAllRoutes:(NSData *)routedata{ 

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:routedata options:0 error:NULL]; 



for (NSDictionary *annnotationobject in json) { 

    NSArray *polyarray = [[NSArray alloc] initWithArray:[annnotationobject objectForKey:@"polyline"]]; 
    NSDictionary *polyDict = [[NSDictionary alloc] initWithDictionary:[polyarray objectAtIndex:0]]; 
    //NSLog(@"keys = %@",[polyDict allKeys]); 
    //NSLog(@"values = %@",[polyDict allValues]); 

    NSInteger pointsCount = polyarray.count; 

    CLLocationCoordinate2D pointsToUse[pointsCount]; 

    for(int i = 0; i < pointsCount; i++){ 
     NSString *lat = polyDict[@"lat"]; 
     NSString *lng = polyDict[@"lng"]; 
     CLLocationDegrees latitude = [lat doubleValue]; 
     CLLocationDegrees longitude = [lng doubleValue]; 
     pointsToUse[i] = CLLocationCoordinate2DMake(latitude, longitude); 


    } 


    MKPolyline *myPolyline = [MKPolyline polylineWithCoordinates:pointsToUse count:pointsCount]; 

    [self.mapView addOverlay:myPolyline]; 


} 

} 

路線數據當屬:究竟

"polyline": [ 
     { 
      "lat": 43.02038, 
      "lng": -87.897706 
     }, 
     { 
      "lat": 43.008363, 
      "lng": -87.892578 
     }, 
     { 
      "lat": 43.006454, 
      "lng": -87.891977 
     }, 
     { 
      "lat": 43.005188, 
      "lng": -87.891827 
     }, 
     { 
      "lat": 43.004029, 
      "lng": -87.891891 
     }, 
     { 
      "lat": 43.00302, 
      "lng": -87.89202 
     }, 
     { 
      "lat": 43.00184, 
      "lng": -87.892106 
     } 
    ], 

每一點地塊如預期,它只是沒有繪製線條將它們連接起來。遇到類似情況的其他人很困難。歡迎所有幫助/建議。如果需要可以提供額外的代碼。

回答

1

「折線」元素是一個字典數組(每個字典都有線中每個點的座標)。

pointsCount設置爲「多段線」中的點數,然後for-i循環填充pointsToUse C數組。

問題是座標始終取自polyDict,其中在循環內部永不改變。

polyDict設置爲多段線中的第一個座標,並且在for-i循環中從不更新。
所以你最終得到一個折線,所有的點都具有相同的座標。

如果您有多條多段線,最終將出現「點圖」。


爲了解決這個問題,刪除此行

NSDictionary *polyDict = [polyarray objectAtIndex:i]; 

現在polyDict將指向:

NSDictionary *polyDict = [[NSDictionary alloc] initWithDictionary: 
          [polyarray objectAtIndex:0]]; 

NSString *lat = ...前添加了for-i循環內這條線到循環迭代時的i th座標。


另外,我假定你已經實現rendererForOverlay並設置地圖視圖的delegate(否則什麼也不會顯示)。



無關,但請注意,您不需要 alloc + initNSDictionarypolyDict - 只是得到一個最早已在 polyarray的參考。

同樣的事情會爲polyarray - 只是參考之一annotationobject

NSArray *polyarray = [annnotationobject objectForKey:@"polyline"]; 
+0

謝謝你的教訓安娜,那完美。 – WiseGuy