有一些关于这方面的教程和问题,但我还不够了解如何将它们实现到我的特定应用程序中。我从 URL 获取 JSON 注释数据并对其进行解析并将每个注释添加到 for 循环中。我想在每个注释上添加一个链接以打开地图以获取路线。
这是我的ViewController.H
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <MapKit/MapKit.h>
//MAP Setup
@interface ViewController : UIViewController <MKMapViewDelegate>
//map setup
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) NSMutableData *downloadData;
//- (IBAction)refreshTapped:(id)sender;
@end
和我的ViewController.m
- (void)viewDidLoad
{
////////////////////////
//Connection to download JSON map info
////////////////////////
self.downloadData = [NSMutableData new];
NSURL *requestURL2 = [NSURL URLWithString:@"http:OMITTED"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL2];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//scroller
[scroller setScrollEnabled:YES];
[scroller setContentSize:CGSizeMake(320,900)];
[super viewDidLoad];
//Map
[self.mapView.userLocation addObserver:self
forKeyPath:@"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:nil];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
id parsed = [NSJSONSerialization JSONObjectWithData:_downloadData options:kNilOptions error:nil];
////////////////////////
//Iterating and adding annotations
////////////////////////
for (NSDictionary *pointInfo in parsed)
{
NSLog([pointInfo objectForKey:@"name"]);
double xCoord = [(NSNumber*)[pointInfo objectForKey:@"lat"] doubleValue];
double yCoord = [(NSNumber*)[pointInfo objectForKey:@"lon"] doubleValue];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(xCoord, yCoord);
MKPointAnnotation *point = [MKPointAnnotation new];
point.coordinate = coords;
point.title = [pointInfo objectForKey:@"name"];
[self.mapView addAnnotation:point];// or whatever your map view's variable name is
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//centers map on user loc and then allows for movement of map without re-centering on userlocation check.
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([self.mapView showsUserLocation])
{
MKCoordinateRegion region;
region.center = self.mapView.userLocation.coordinate;
MKCoordinateSpan span;
span.latitudeDelta = .50; // Change these values to change the zoom
span.longitudeDelta = .50;
region.span = span;
[self.mapView setRegion:region animated:YES];
self.mapView.showsUserLocation = NO;}
}
- (void)dealloc
{
[self.mapView.userLocation removeObserver:self forKeyPath:@"location"];
[self.mapView removeFromSuperview]; // release crashes app
self.mapView = nil;
}
@end