2012-02-04 3 views
0

Я разбираю два json-канала. Первый json-канал анализирует аптеки определенного региона и заполняет карту, второй канал анализирует список гамбургеров, присутствующих в этом регионе, и заполняет карту. Я хочу установить контакты, представляющие первый канал красного цвета, а второй - зеленым цветом. Я noob, вы могли бы мне помочь? Ниже приведен код.Как установить два разных цвета булавки при заполнении mapview

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [email protected]"Map"; 
    [self secondMap]; 
    [self firstMap]; 
} 

-(void)secondMap 
{ 
    jsonurl1=[NSURL URLWithString:@"http://dev-parkguiden.knutpunkten.se/Api/GetPharmacyJson"]; 
    NSURLRequest *request1 = [NSURLRequest requestWithURL:jsonurl1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    connection1=[[[NSURLConnection alloc] initWithRequest:request1 delegate:self] autorelease]; 

    self.jsonData1=[[NSString alloc]initWithContentsOfURL:jsonurl1]; 

    self.jsonArray1 = [self.jsonData1 objectFromJSONString]; 
    NSLog(@"blah:%@",jsonArray1); 
    items= [self.jsonArray1 objectForKey:@"pharmacies"]; 
    NSDictionary *bam=[items valueForKey:@"location"]; 

    for (NSDictionary *item in bam) 
    { 
     latitude=[[item valueForKey:@"latitude"] floatValue]; 
     longitude=[[item valueForKey:@"longitude"] floatValue]; 

     NSLog(@"String3:%f",latitude); 
     NSLog(@"String4:%f",longitude); 
     Place* home = [[[Place alloc] init] autorelease]; 
     home.name = [item valueForKey:@"Name"]; 
     // home.description=[item valueForKey:@"description"]; 
     home.latitude = latitude; 
     home.longitude = longitude; 

     PlaceMark *from = [[[PlaceMark alloc] initWithPlace:home] autorelease];     
     [mapView addAnnotation:from]; 

     NSLog(@"the latitude:%f",latitude); 
     NSLog(@"the latitude:%f",longitude); 
     [self centerMap]; 
    } 
} 

-(void)firstMap 
{ 
    jsonurl=[NSURL URLWithString:@"http://dev-parkguiden.knutpunkten.se/Api/WhereIam?longitude=18.105469&latitude=59.304786&distance=100"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:jsonurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    connection1=[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 

    //NSLog(@"jsonurl:%@",jsonurl); 
    self.jsonData=[[NSString alloc]initWithContentsOfURL:jsonurl]; 

    self.jsonArray = [self.jsonData objectFromJSONString]; 
    NSLog(@"blah:%@",jsonArray); 
    items = [self.jsonArray objectForKey:@"parks"]; 

    story = [[NSMutableArray array]retain]; 
    media1 = [[NSMutableArray array]retain]; 
    url=[[NSMutableArray array]retain]; 
    descriptiondesc=[[NSMutableArray array]retain]; 
    for (NSDictionary *item in items) 
    { 
     latitude=[[item valueForKey:@"latitude"] floatValue]; 
     longitude=[[item valueForKey:@"longitude"] floatValue]; 

     NSLog(@"String1:%f",latitude); 
     NSLog(@"String2:%f",longitude); 
     Place* home = [[[Place alloc] init] autorelease]; 
     home.name = [item valueForKey:@"Name"]; 
     // home.description=[item valueForKey:@"description"]; 
     home.latitude = latitude; 
     home.longitude = longitude; 

     PlaceMark *from = [[[PlaceMark alloc] initWithPlace:home] autorelease];    
     [mapView addAnnotation:from]; 

     NSLog(@"the latitude:%f",latitude); 
     NSLog(@"the latitude:%f",longitude); 
     [self centerMap]; 
    } 
} 

-(void) centerMap 
{ 
    MKCoordinateRegion region; 
    MKCoordinateSpan span; 
    span.longitudeDelta=0.1; 
    span.latitudeDelta=0.1; 

    CLLocationCoordinate2D location=mapView.userLocation.coordinate; 
    location.latitude=latitude; 
    location.longitude=longitude; 
    region.span=span; 
    region.center=location; 

    [mapView setRegion:region animated:TRUE]; 
    [mapView regionThatFits:region]; 
} 

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id  <MKAnnotation>)annotation 
{ 
    mapView.mapType=MKMapTypeHybrid; 
    mapView.showsUserLocation=YES; 
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"]; 
    annView.pinColor = MKPinAnnotationColorGreen; 
    annView.animatesDrop=TRUE; 
    annView.canShowCallout = YES; 
    annView.calloutOffset = CGPointMake(-5, 5); 

    UIButton *detailButton=[UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
    //NSInteger annotationValue=[self.annotations indexOfObject:annotation]; 

    [detailButton addTarget:self action:@selector(showDetailView)  forControlEvents:UIControlEventTouchUpInside]; 
    annView.rightCalloutAccessoryView=detailButton; 
    return annView; 
} 
+0

Не устанавливайте mapType и показываетUserLocation в viewForNnotation, который вызывается для каждой аннотации. Эти свойства применяются ко всей карте и более уместны для установки в viewDidLoad. – Anna

ответ

2

Он смотрит на меня, как вы создали PlaceMark класс, который соответствует протоколу MKAnnotation. Итак, что вы можете сделать, это добавить к нему свойство, которое идентифицирует, является ли это аптекой или магазином для гамбургеров, или просто устанавливает свой цвет. Затем, когда вы создаете его, убедитесь, что вы установили, что свойство:

PlaceMark *from = [[[PlaceMark alloc] initWithPlace:home] autorelease]; 
from.colorName = @"red"; 
[mapView addAnnotation:from]; 

Затем в методе mapView:viewForAnnotation:, что вам нужно, чтобы захватить это из аннотации вы прошли.

- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id  <MKAnnotation>)annotation 
{ 
    PlaceMark *placeMark = (PlaceMark*) annotation; 

    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"]; 

    if([placeMark.colorName isEqualToString:@"red"]) { 
     annView.pinColor = MKPinAnnotationColorRed; 
    } else { 
     annView.pinColor = MKPinAnnotationColorGreen; 
    } 

    ... 
} 
+0

mkay даст попробовать – stephensam

+0

, если i m использовать from.colorName, я получаю ошибку.может ли я использовать ivar "colorName" в моем PlaceMark? – stephensam

+0

i синтезировал переменную NSString в классе PlaceMark и попробовал вышеуказанный модуль, который вы дали. I смог отличить pincolor для двух разных url'ов. Когда первые три контакта загружаются .im получают тень, и мое приложение разбивается. .. NSLog выглядит примерно так ... [MKUserLocation colorName]: непризнанный селектор отправлен в экземпляр 0x1dc270 ... cud u help me out – stephensam

Смежные вопросы