试试这个代码,我认为这对你有用。在 .h 文件中添加此代码
#import "CoreLocation/CoreLocation.h"
#import "MapKit/MapKit.h"
@interface AddressAnnotation : NSObject<MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
}
@end
@interface NearestPropertyMatchViewController : UIViewController<MKMapViewDelegate> {
CLLocationManager *locationManager;
IBOutlet MKMapView *searchMap;
NSMutableArray *searchListArray;
AddressAnnotation *addAnnotation;
}
-(CLLocationCoordinate2D) addressLocation:(NSString *)str;
@property (nonatomic, retain) CLLocationManager *locationManager;
@end
在 .m 文件中添加此代码。
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
NSLog(@"dLatitude : %@", latitude);
NSLog(@"dLongitude : %@",longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
region.span=span;
for(int i=0;i<[regestrationArray count];i++)
{
CLLocationCoordinate2D location = [self addressLocation:[regestrationArray objectAtIndex:i]];
region.center=location;
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[searchMap addAnnotation:addAnnotation];
[searchMap setRegion:region animated:TRUE];
[searchMap regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation :(NSString *)str
{
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:@","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
NSLog(@" lati=%f lon=%f",latitude,longitude);
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}