I want to load map on MKMapView.
Basically what i want to do is,
I want to load Particular Venue in my MapView.
My Database contains lot of Venues, according to requirement, i am fetching Venue and i want to load that Venue in my mapView.
for eg: I got this as Venue: #"100 Oxford Street, London, W1D 1LL, 020 7636 0933" from Database, then i want to load this location in my mapView
Thanks in advance.
EDIT:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[geocoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
NSLog(#"_venue:=%f",loc.coordinate);
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[MapVw addAnnotation:venueAnnotation];
}
}
];
- (IBAction)BtnClick:(id)sender {
NSLog(#"Map ");
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"100 Oxford Street, London, W1D 1LL, 020 7636 0933"
completionHandler:^(NSArray* placemarks, NSError* error)
{
if (placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
[self.MapView addAnnotation:placemark];
CLLocationCoordinate2D _venue = placemark.coordinate;
[self.MapView setCenterCoordinate:_venue];
MKCoordinateRegion region = self.MapView.region;
region.span.longitudeDelta = 1.0;
region.span.latitudeDelta = 1.0;
[self.MapView setRegion:region animated:YES];
}
}
];
}
Steps:
1. Import CoreLocation.framework and MapKit.framework.
2. Use CoreLocation class Geocoder's method :
geoCodeAddressString:completionHandler:
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[_geoCoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
}
});
]
[self performSelector:#selector(createVenueAnnotation) withObject:nil afterDelay:5];
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]init];
[_mapView addSubview:activity];
[activity startAnimating];
Step 3. If you want to place a MKPointAnnotation on the venue point.
- (void)createVenueAnnotation{
[activity stopAnimating];
[activity removeFromSuperview];
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[_mapView addAnnotation:venueAnnotation];
}
Step 4: Center your map around the venue.
// you need to call this function
- (void)centerMapAroundVenue
{
MKMapRect rect = MKMapRectNull;
MKMapPoint venuePoint = MKMapPointForCoordinate(_venue);
rect = MKMapRectUnion(rect, MKMapRectMake(venuePoint .x, venuePoint .y, 0, 0));
MKCoordinateRegion region = MKCoordinateRegionForMapRect(rect);
[_mapView setRegion:region animated:YES];
}
Here is simple scenario :
Get the Co-ordinates of the Address using GeoCoder
Using the Co-ordinatation ,Add the Annotation to the MapView.
Do something Like this to get the CLlocationCoordinate :
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
double latitude = 0, longitude = 0;
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
if (result) {
NSScanner *scanner = [NSScanner scannerWithString:result];
if ([scanner scanUpToString:#"\"lat\" :" intoString:nil] && [scanner scanString:#"\"lat\" :" intoString:nil]) {
[scanner scanDouble:&latitude];
if ([scanner scanUpToString:#"\"lng\" :" intoString:nil] && [scanner scanString:#"\"lng\" :" intoString:nil]) {
[scanner scanDouble:&longitude];
}
}
}
CLLocationCoordinate2D center;
center.latitude = latitude;
center.longitude = longitude;
return center;
}
Using the Center just add the annotation to the MapView.
[self.mapView addAnnotation:<annotationName>];
Plz go through this link For more info.
Hope this helps.
Related
I have looked at other questions in stackoverflow that are closely related to my question however my issue is a bit different. Here, the code works fine on iPad but not my iPhone. My iPad will load all 300+ annotations correctly but my iPhone will only load only 80 of them. I'm not sure if this is due to the amount of memory on the iPhone because it does the same thing when I test on the simulator. Below you will find my sample code.
#interface MOVmapViewController ()
#end
#define VA_LATITUDE 37.413754;
#define VA_LONGITUDE -79.142246;
//Span
#define THE_SPAN 5.50f;
#implementation MOVmapViewController
#synthesize myMapView;
-(IBAction)findmylocation:(id)sender {
myMapView.showsUserLocation = YES;
myMapView.delegate = MKMapTypeStandard;
[myMapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
}
-(IBAction)setmaptype:(id)sender {
switch (((UISegmentedControl *)sender).selectedSegmentIndex) {
case 0:
myMapView.mapType = MKMapTypeStandard;
break;
case 1:
myMapView.mapType = MKMapTypeSatellite;
break;
case 2:
myMapView.mapType = MKMapTypeHybrid;
break;
default:
myMapView.mapType = MKMapTypeStandard;
break;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typiclly from a nib.
//Create the region
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = VA_LATITUDE;
center.longitude = VA_LONGITUDE;
//Span
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
//Set our mapView
[myMapView setRegion:myRegion animated:YES];
//Annotations
//Abingdon Lodge No. 48
NSString *abingdon = #"325 W Main Street Abingdon, Virginia 24210";
CLGeocoder *abingdongeo = [[CLGeocoder alloc] init];
[abingdongeo geocodeAddressString:abingdon completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"Abingdon Lodge No. 48";
point.subtitle = #"Abingdon, VA";
[self.myMapView addAnnotation:point]; }}];
//York Lodge No. 12
NSString *york = #"14411 Black Hollow Road Abingdon, Virginia 24210";
CLGeocoder *yorkgeo = [[CLGeocoder alloc] init];
[yorkgeo geocodeAddressString:york completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"York Lodge No. 12";
point.subtitle = #"Abingdon, VA";
[self.myMapView addAnnotation:point]; }}];
//Alberene Lodge No. 277
NSString *alberene = #"2722 Plank Road Alberene, Virginia 22959";
CLGeocoder *alberenegeo = [[CLGeocoder alloc] init];
[alberenegeo geocodeAddressString:alberene completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"Alberene Lodge No. 277";
point.subtitle = #"Alberene, VA";
[self.myMapView addAnnotation:point]; }}];
//A. Douglas Smith, Jr. Lodge of Research No. 1949
NSString *douglas = #"101 Callahan Drive Alexandria, Virginia 22301";
CLGeocoder *douglasgeo = [[CLGeocoder alloc] init];
[douglasgeo geocodeAddressString:douglas completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"A. Douglas Smith, Jr. Lodge of Research No. 1949";
point.subtitle = #"Alexandria, VA";
[self.myMapView addAnnotation:point]; }}];
//Alexandria-Washington Lodge No. 22 same location as above use lat/long
CLLocationCoordinate2D washington;
washington.latitude = 38.806758;
washington.longitude = -77.065251;
Annotation *alexandriawashingtonlodge = [Annotation alloc];
alexandriawashingtonlodge.coordinate = washington;
alexandriawashingtonlodge.title = #"Alexandria-Washington Lodge No. 22";
alexandriawashingtonlodge.subtitle = #"Alexandria, VA";
[self.myMapView addAnnotation:alexandriawashingtonlodge];
This list continues for a total of about 310 lodge locations.
Use like this,
NSString *abingdon = #"325 W Main Street Abingdon, Virginia 24210";
CLGeocoder *abingdongeo = [[CLGeocoder alloc] init];
[abingdongeo geocodeAddressString:abingdon completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"Abingdon Lodge No. 48";
point.subtitle = #"Abingdon, VA";
// Set your region using placemark (not point)
MKCoordinateRegion region = self.mapView.region;
region.center = placemark.region.center;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
// Add point (not placemark) to the mapView
[self.mapView setRegion:region animated:YES];
[self.mapView addAnnotation:point];
// Select the PointAnnotation programatically
[self.mapView selectAnnotation:point animated:NO]; }}];
The reason that some of my annotations are not showing up is because I'm calling on CLGeocoder to many times. Here is how I fixed the issue.
//Columbia Lodge No. 285
CLLocationCoordinate2D columbia;
columbia.latitude = 38.895746;
columbia.longitude = -77.106511;
Annotation *columbialodge = [[Annotation alloc] init];
columbialodge.coordinate = columbia;
columbialodge.title = #"Columbia Lodge No. 285";
columbialodge.subtitle = #"Arlington, VA";
[self.myMapView addAnnotation:columbialodge];
I'v converted all my of address to Lat long. Which has cut down on memory usage as well.
As much as I enjoyed just putting in the address it looks like CLGeocoder is just taking up to many resources.
I have "googled" this question a few times today with no luck. I would like to know if it is possible to create an annotation in Mapview from an address rather than using the lat/Long method. My current code is below.
//1. Create a coordinate for use with the annotation
CLLocationCoordinate2D Sharon;
Sharon.latitude = 38.952223;
Sharon.longitude = -77.193646;
Annotation *myAnnotation = [Annotation alloc];
myAnnotation.coordinate = Sharon;
myAnnotation.title = #"Sharon Lodge #327";
myAnnotation.subtitle = #"McLean, VA";
Try like this,
NSString *location = "some address, state, and zip";
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
MKCoordinateRegion region = self.mapView.region;
region.center = placemark.region.center;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
[self.mapView setRegion:region animated:YES];
[self.mapView addAnnotation:placemark];
}
];
for annotation title and subtitle,
CLPlacemark *topResult = [placemarks objectAtIndex:0];
// Create an MLPlacemark
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
// Create an editable PointAnnotation, using placemark's coordinates, and set your own title/subtitle
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = placemark.coordinate;
point.title = #"Sample Location";
point.subtitle = #"Sample Subtitle";
// Set your region using placemark (not point)
MKCoordinateRegion region = self.mapView.region;
region.center = placemark.region.center;
region.span.longitudeDelta /= 8.0;
region.span.latitudeDelta /= 8.0;
// Add point (not placemark) to the mapView
[self.mapView setRegion:region animated:YES];
[self.mapView addAnnotation:point];
// Select the PointAnnotation programatically
[self.mapView selectAnnotation:point animated:NO];
You can get lat long from an address using google api or CLGeocoder
google api
Link 1 Link 2
CLGeocoder
-(id)getAnnotationAryFromAddress
{
CLGeocoder *geocoder2 = [[CLGeocoder alloc] init];
NSString *addressString = "string contain address, city, state and zip";
[geocoder2 geocodeAddressString:addressString
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
//NSLog(#"Geocode failed with error: %#", error);
return;
}
if (placemarks && placemarks.count > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
RegionAnnotation *annotation = [[RegionAnnotation alloc] init];
CLLocationCoordinate2D theCoordinate1;
theCoordinate1 = location.coordinate;
annotation.title = #"Title";
annotation.subtitle = #"SubTitle";
annotation.tag = i;
annotation.coordinate = theCoordinate1;
[self.mapView addAnnotation:annotation];
}
}];
}
return self;
}
I want to get the location name from the coordinate value. Here is code,
- (void)viewWillAppear:(BOOL)animated {
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 39.281516;
zoomLocation.longitude= -76.580806;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.5*METERS_PER_MILE, 0.5*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
[_mapView setRegion:adjustedRegion animated:YES];
}
So, From that Latitude and longitude , i want to know that location name.
The Below code shall work in ios5 and above
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:32.00 longitude:21.322]; //insert your coordinates
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark) {
NSLog(#"placemark %#",placemark);
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
NSLog(#"placemark %#",placemark.region);
NSLog(#"placemark %#",placemark.country); // Give Country Name
NSLog(#"placemark %#",placemark.locality); // Extract the city name
NSLog(#"location %#",placemark.name);
NSLog(#"location %#",placemark.ocean);
NSLog(#"location %#",placemark.postalCode);
NSLog(#"location %#",placemark.subLocality);
NSLog(#"location %#",placemark.location);
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
}
else {
NSLog(#"Could not locate");
}
}
];
-(NSString *)getAddressFromLatLon:(double)pdblLatitude withLongitude:(double)pdblLongitude
{
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pdblLatitude, pdblLongitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
// NSLog(#"%#",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
return [locationString substringFromIndex:6];
}
Use this method
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation: zoomLocation completionHandler:^(NSArray* placemarks, NSError* error){
}
];
In iOS 5.0 and later, you can use CLGeocoder of Core Location framework, as for iOS lower than 5.0, MKReverseGeocoder of Map Kit Framework. Good luck!
Here is block to get address string from current location
in .h file
typedef void(^addressCompletionBlock)(NSString *);
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock;
in .m file
#pragma mark - Get Address
-(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletionBlock)completionBlock
{
//Example URL
//NSString *urlString = #"http://maps.googleapis.com/maps/api/geocode/json?latlng=23.033915,72.524267&sensor=true_or_false";
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true_or_false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[locationString dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSString *strFormatedAddress = [[[jsonObject valueForKey:#"results"] objectAtIndex:0] valueForKey:#"formatted_address"];
completionBlock(strFormatedAddress);
}
and to call function
CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:[SharedObj.current_Lat floatValue] longitude:[SharedObj.current_Long floatValue]];
[self getAddressFromLocation:currentLocation complationBlock:^(NSString * address) {
if(address) {
NSLog(#"Address:: %#",address);
}
}];
I need to display multiple annonation views in MKMapKit..I use this code..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
DisplayMap *ann = [[DisplayMap alloc] init];
//NSLog(#"xapp.arrplacename:%d",[xapp.arrplacename count]);
for (i=0;i<=[arrplacename count]-1;i++)
{
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
//arrplacename contains the address of the locations
NSString *straddress=[arrplacename objectAtIndex:i];
NSString *strregion=#"";
NSString *strs=[straddress stringByAppendingString: strregion];
// lbladdress.text=strs;
// NSString add=strs;
// here you define the url setting your address
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[strs stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(#"US: %#",urlString);
// then you get the response string here
NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
NSLog(#"loaction strings%#",locationString);
// now you can create an array splitting the response values using the ","
//[listItems addObject:locationString];
listItems = [locationString componentsSeparatedByString:#","];
NSLog(#"A: %#",[xapp.listItems objectAtIndex:2]);
// define latitude and longitude variables
double latitude = 0.0;
double longitude = 0.0;
NSString *strlatitude;
NSString *strlongitude;
strlatitude=[xapp.listItems objectAtIndex:2];
strlongitude=[xapp.listItems objectAtIndex:3];
float stringFloat = [strlatitude floatValue];
float string1Float = [strlongitude floatValue];
// if your array has inside the sctructure you aspect (4 values as described in my previous post) and the first value is like "200" (OK result)
if([xapp.listItems count] >= 4 && [[xapp.listItems objectAtIndex:0] isEqualToString:#"200"])
{
// not sure if you need the accurancy parameter
//accurancy = [[listItems objectAtIndex:1] intValue];
// here you can get your values
// latitude = [[listItems objectAtIndex:2] doubleValue];
//longitude = [[listItems objectAtIndex:3] doubleValue];
latitude = stringFloat;
longitude = string1Float;
}
else {
NSLog(#"Error on map");
}
region.center.latitude = latitude;
region.center.longitude = longitude;
NSLog(#"latitude:%g",region.center.latitude);
// region.center.latitude = 42.7157850;
// region.center.longitude = 27.56470180;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
ann.title = [xapp.arrplacename objectAtIndex:i];
ann.subtitle = [xapp.arrplacename objectAtIndex:i];
ann.coordinate = region.center;
[mapView addAnnotation:ann];
}
}
I do have some problems in this code....all the coordnates are not added to the listitems array..I can see only the objects that are added atlast....
This is the delegates I add for displaying the annonation in my map..
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{
NSLog(#"ssssss");
double latitude = 0, longitude = 0;
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
if (result) {
NSScanner *scanner = [NSScanner scannerWithString:result];
if ([scanner scanUpToString:#"\"lat\":" intoString:nil] && [scanner scanString:#"\"lat\":" intoString:nil]) {
[scanner scanDouble:&latitude];
if ([scanner scanUpToString:#"\"lng\":" intoString:nil] && [scanner scanString:#"\"lng\":" intoString:nil]) {
[scanner scanDouble:&longitude];
}
}
}
CLLocationCoordinate2D center;
center.latitude = latitude;
center.longitude = longitude;
return center;
}
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = nil;
NSLog(#"pinnview before release %d",[pinView retainCount]);
if (pinView !=nil) {
pinView =nil;
[pinView release];
}
NSLog(#"pinnview after release %d",[pinView retainCount]);
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"your-pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( counting < [mapView.annotations count])
{
counting++;
pinView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
/* for(DisplayMap* a in mapView.annotations)
{
if (annotation == a){
pinView.image =
[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:a.image ofType:nil]];
}
}*/
pinView.centerOffset= CGPointMake(0,-10);
pinView.canShowCallout = YES;
}
}
// return pinView;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(#"enter");
[mapView selectAnnotation:[[mapView annotations] lastObject] animated:YES];
}
Delegates are called only once eventhough I'm using [mapView addAnnotation:ann]; inside the for loop...And it shows pin only for the last item tatz added in the array...How can I overcome this????
You are allocating and initializing 'ann' only once before the for loop starts, and you are altering the same and adding it again and again into Map. Thats why you are getting only one annotation.
Move this line inside for loop and try,
DisplayMap *ann = [[DisplayMap alloc] init];
How to load Google Map - Specific area map - specified address by user in UItextField?
Ok. I Got the solution by r&d.
See the code following.
-(IBAction)showAddress // after adding the Address into textField - button pressed{
[addressField resignFirstResponder];
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.05;
span.longitudeDelta=0.05;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil)
{
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation=nil;
}
addAnnotation = [ [AddressAnnotation alloc] initWithCoordinate:location];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
[mapView addAnnotation:addAnnotation];
}
-(CLLocationCoordinate2D) addressLocation {
// NSString *urlString = [[NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *urlString=[NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
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
{
NSLog(#"Error");
}
CLLocationCoordinate2D location;
location.latitude=latitude;
location.longitude=longitude;
return location;
}