to show route from current location to moving car destination - iphone

I am tried showing route from current location to destination using Google map but i want to show route from moving object to my current location?

I hope you can find a way to implement your functionality from following URL
http://code4app.net/category/mapview

use nvpolyline something like
(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation {
if ([annotation isKindOfClass:[NVPolylineAnnotation class]]) {
return [[[NVPolylineAnnotationView alloc] initWithAnnotation:annotation mapView:map] autorelease];
}
return nil;
}
(void) mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
// fixes that some marker are behind the polyline
if ([Appdelegate.CrashUserArray count] > 0)
{
for (int i = 0; i < [Appdelegate.CrashUserArray count]; i ++)
{
for (int j = 0; j < [views count]; j++) {
MKAnnotationView *view = [views objectAtIndex:j];
if ([view isKindOfClass:[NVPolylineAnnotationView class]])
{
[[view superview] sendSubviewToBack:view];
//view.image=[UIImage imageNamed:#"close_button.png"];
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
{
[self updatePolylineAnnotationView];
}
}
else {
if ([[Appdelegate.CrashUserArray objectAtIndex:i] count] > 0) {
nextviewbtn=[[UIButton alloc]init];
nextviewbtn.frame=CGRectMake(10,10,13,22);
[nextviewbtn addTarget:self action:#selector(OpenUser:) forControlEvents:UIControlEventTouchUpInside];
nextviewbtn.tag=i;
[nextviewbtn setBackgroundImage:[UIImage imageNamed:#"right_arrow.png"] forState:UIControlStateNormal];
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: [[[Appdelegate.CrashUserArray objectAtIndex:i]objectAtIndex:0] objectForKey:#"userphoto_47"]]];
if ( data == nil )
return;
dispatch_async(dispatch_get_main_queue(), ^{
view.image = [UIImage imageWithData: data];
view.rightCalloutAccessoryView=nextviewbtn;
});
[data release];
});
}
}
}
}
}
[mapView setShowsUserLocation:NO];
}
(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
SparkFromMapViewController *spark=[[SparkFromMapViewController alloc]initWithNibName:#"SparkFromMapViewController" bundle:nil];
if ([[Appdelegate.CrashUserDetailArray objectAtIndex:0] count] > 0)
{
spark.userdetailarray=[[NSMutableArray alloc] init];
spark.userdetailarray=[Appdelegate.CrashUserDetailArray objectAtIndex:0];
}
[self.navigationController pushViewController:spark animated:NO];
[spark release];
}
(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
NSString *reqSysVer = #"4.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) {
[self updatePolylineAnnotationView];
}
}
(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
if([annotationView isKindOfClass:[RegionAnnotationView class]]) {
RegionAnnotationView *regionView = (RegionAnnotationView *)annotationView;
RegionAnnotation *regionAnnotation = (RegionAnnotation *)regionView.annotation;
if (newState == MKAnnotationViewDragStateStarting) {
[regionView removeRadiusOverlay];
[locationmanager stopMonitoringForRegion:regionAnnotation.region];
}
if (oldState == MKAnnotationViewDragStateDragging && newState == MKAnnotationViewDragStateEnding) {
[regionView updateRadiusOverlay];
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
CLRegion *newRegion = [[CLRegion alloc] initCircularRegionWithCenter:regionAnnotation.coordinate radius:1000.0 identifier:[NSString stringWithFormat:#"%f, %f", [def floatForKey:#"currentlati"],[def floatForKey:#"currentlongi"]]];
regionAnnotation.region = newRegion;
// [locationmanager startMonitoringForRegion:regionAnnotation.region desiredAccuracy:kCLLocationAccuracyBest];
}
}
}
-(void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
oldlocation.latitude = aUserLocation.coordinate.latitude;
oldlocation.longitude = aUserLocation.coordinate.longitude;
region.span = span;
region.center = oldlocation;
NSArray *points = [NSArray arrayWithObjects:
[[[CLLocation alloc] initWithLatitude:45.43894 longitude:-73.7396] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44628 longitude:-73.74119] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44649 longitude:-73.74106999999999] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44665999999999 longitude:-73.7409] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44665999999999 longitude:-73.7409] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44676 longitude:-73.74073] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44707999999999 longitude:-73.73990000000001] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44748 longitude:-73.73856000000001] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44748 longitude:-73.73856000000001] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44834 longitude:-73.73581] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44857999999999 longitude:-73.73475999999999] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44863000000001 longitude:-73.73417000000001] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44863000000001 longitude:-73.73300999999999] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44795 longitude:-73.7008] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44784 longitude:-73.69398] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44775 longitude:-73.69092000000001] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44743999999999 longitude:-73.68584] autorelease],
[[[CLLocation alloc] initWithLatitude:45.44728 longitude:-73.68165999999999] autorelease],
[[[CLLocation alloc] initWithLatitude:45.48679000000001 longitude:-73.59443] autorelease],
nil];
NVPolylineAnnotation *annotation = [[[NVPolylineAnnotation alloc] initWithPoints:points mapView:map] autorelease];
[map addAnnotation:annotation];
[loc release];
[aMapView setRegion:region animated:YES];
NSLog(#"uncomment this when you want to upload record");
}
}
by this method you can draw path on map

Related

Show multiple pins on MKMap iPhone

Hello friend in my application i am showing multiple pins on mapview. I have two mutablearray first for latitude and second for longitude each array have 10 values as i am showing bellow code in my method:
- (void)showAddressAllBusiness {
annotationsarray=[[NSMutableArray alloc] init];
NSLog(#"%d",[listOfLatitude count]);
NSLog(#"%d",[listOfLongitude count]);
NSLog(#"%d",[listOfPlaceName count]);
for (int i =0;i < [listOfLatitude count]; i++) {
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = [[listOfLatitude objectAtIndex:i] doubleValue];
region.center.longitude = [[listOfLongitude objectAtIndex:i] doubleValue];
region.span.longitudeDelta = 0.1f;
region.span.latitudeDelta = 0.1f;
[self.mapViewCityGuide setRegion:region animated:YES];
[self.mapViewCityGuide setZoomEnabled:YES];
addAnnotation = [[AddressAnnotation alloc]init];
addAnnotation.mTitle = [NSString stringWithFormat:#"%#",[listOfPlaceName objectAtIndex:i]];
addAnnotation.coordinate = region.center;
[self.mapViewCityGuide addAnnotation:addAnnotation];
[annotationsarray addObject:addAnnotation];
}
NSLog(#"%d",[self.mapViewCityGuide.annotations count]);
[self centerMap];
}
when i am using latitude and longitude array values which is appear from webservice then
this code is not working fine and i am debugg the code then mapViewCityGuide getting nil or 0x0.
If i am using hard code latitude and longitude value as mention bellow in the array and call this method then it will show all pins on map how can i solve this problem
listOfPlaceName = [[NSMutableArray alloc] initWithObjects:#"test",#"test",#"test",#"pithempur",#"test",#"test",#"test",#"test", nil];
listOfLatitude = [[NSMutableArray alloc] initWithObjects:#"22.71957",#"23.17930",#"22.96123",#"22.60987",#"22.45260",#"22.55244",#"22.60000",#"22.68330", nil];
listOfLongitude = [[NSMutableArray alloc] initWithObjects:#"75.85773",#"75.78491",#"76.05141",#"75.69644",#"75.94197",#"75.75653",#"75.30000",#"75.61670", nil];
[self showAddressAllBusiness];
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
mapView.delegate=self;
[mapView removeAnnotations:mapView.annotations];
NSMutableArray* annotations=[[NSMutableArray alloc] init];
for (int j=0; j<10; j++)
{
CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = [[NSString stringWithFormat:#"%i",10+j]doubleValue];
theCoordinate1.longitude = [[NSString stringWithFormat:#"%i",72+j]doubleValue];
//my annotation is mkannotation class
MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];
myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=[NSString stringWithFormat:#"locatiion %i",j];
[mapView addAnnotation:myAnnotation1];
[annotations addObject:myAnnotation1];
}
NSLog(#"%d",[annotations count]);
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
NSLog(#"fly to on");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapView.visibleMapRect = flyTo;
}
#pragma mark MKMapViewDelegate
/*
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kml viewForOverlay:overlay];
}
*/
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
if ([annotation isKindOfClass:[MyAnnotation class]])
{
static NSString *AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
if (!pinView)
{
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
}
else
{
pinView.annotation = annotation;
pinView.tag=((MyAnnotation *)annotation).tag;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame=CGRectMake(0, 0, 14, 16);
[rightButton setBackgroundImage:[UIImage imageNamed:#"arrow_s5.png"] forState:UIControlStateNormal];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
rightButton.tag=((MyAnnotation *)annotation).tag;
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
return pinView;
}
return nil;
}
*Please try this code:-*
-(void)viewDidLoad
{
CLLocation *userLoc = mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
mapView.delegate=self;
NSMutableArray* annotations=[[NSMutableArray alloc] init];
MyAnnotation* myAnnotation;
for (int i = 0; i<[DataArr count]; i++)
{
CLLocationCoordinate2D theCoordinate;
double a = [[[DataArr objectAtIndex:i] valueForKey:#"lat"] doubleValue];
double b =[[[DataArr objectAtIndex:i] valueForKey:#"lon"] doubleValue];
theCoordinate.latitude = a;
theCoordinate.longitude =b;
myAnnotation=[[MyAnnotation alloc] init];
NSString *str=[NSString stringWithFormat:#"%d",i];
[myAnnotation indexOfAccessibilityElement:str];
myAnnotation.coordinate=theCoordinate;
myAnnotation.title=[[DataArr objectAtIndex:i] valueForKey:#"name"];
myAnnotation.ID_map=i;
[annotations addObject:myAnnotation];
}
for (int i =0; i<[annotations count]; i++)
{
[mapView addAnnotation:[annotations objectAtIndex:i]];
}
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations)
{
NSLog(#"fly to on");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo))
{
flyTo = pointRect;
} else
{
flyTo = MKMapRectUnion(flyTo, pointRect);
//NSLog(#"else-%#",annotationPoint.x);
}
}
// Position the map so that all overlays and annotations are visible on screen.
mapView.visibleMapRect = flyTo;
}
#pragma mark MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
NSLog(#"didSelectAnnotationView");
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"profile.png"]];
pinView.leftCalloutAccessoryView = profileIconView;
[profileIconView release];
return pinView;
}

MapView annotations/pins in iPhone

In my viewDidLoad: method I have set the MapView like this so that if user has selected all the locations then it should show all the locations/pin views and if only one then only one pin view should be shown.
- (void)viewDidLoad{
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
if ([vehicleLabel.text isEqualToString:#"All Vehicles"]) {
MKCoordinateRegion region = {{0.0, 0.0},{0.0, 0.0}};
region.center.latitude = 41.01860;
region.center.longitude = 28.96470;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
Annotations *ann = [[Annotations alloc] init];
ann.title = #"Vehicle A";
ann.subtitle = #"VG 1";
ann.coordinate = region.center;
[mapView addAnnotation:ann];
NSMutableArray* annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = 41.01760;
theCoordinate1.longitude = 30.96470;
CLLocationCoordinate2D theCoordinate2;
theCoordinate2.latitude = 41.01860;
theCoordinate2.longitude = 31.96470;
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.latitude = 41.01360;
theCoordinate3.longitude = 25.96470;
CLLocationCoordinate2D theCoordinate4;
theCoordinate4.latitude = 41.01560;
theCoordinate4.longitude = 27.96470;
Annotations* myAnnotation1=[[Annotations alloc] init];
myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=#"Vehicle B";
myAnnotation1.subtitle=#"Group 1";
Annotations* myAnnotation2=[[Annotations alloc] init];
myAnnotation2.coordinate=theCoordinate2;
myAnnotation2.title=#"Vehicle C";
myAnnotation2.subtitle=#"Group 1";
Annotations* myAnnotation3=[[Annotations alloc] init];
myAnnotation3.coordinate=theCoordinate3;
myAnnotation3.title=#"Vehicle D";
myAnnotation3.subtitle=#"Group 1";
Annotations* myAnnotation4=[[Annotations alloc] init];
myAnnotation4.coordinate=theCoordinate4;
myAnnotation4.title=#"Vehicle E";
myAnnotation4.subtitle=#" Group 1";
[mapView addAnnotation:myAnnotation1];
[mapView addAnnotation:myAnnotation2];
[mapView addAnnotation:myAnnotation3];
[mapView addAnnotation:myAnnotation4];
[annotations addObject:myAnnotation1];
[annotations addObject:myAnnotation2];
[annotations addObject:myAnnotation3];
[annotations addObject:myAnnotation4];
NSLog(#"Annotations: %d",[annotations count]);
}
else {
MKCoordinateRegion region = {{0.0, 0.0},{0.0, 0.0}};
region.center.latitude = 41.01860;
region.center.longitude = 28.96470;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
Annotations *ann = [[Annotations alloc] init];
ann.title = #"Vehicle A";
ann.subtitle = #"VG 1";
ann.coordinate = region.center;
[mapView addAnnotation:ann];
}}
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation{
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"aPin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
} else {
}
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
return pinView;}
And in my PickerView didSelectRow method: I have implemented:
-(void)pickerView:(UIPickerView *)pickerViewG didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if (component == kGroupComponent) {
NSString *selectedState = [self.vehicleGroup objectAtIndex:row];
NSArray *array = [groupVehicles objectForKey:selectedState];
self.vehiclesList = array;
[vehiclePicker selectRow:0 inComponent:kListComponent animated:YES];
[vehiclePicker reloadComponent:kListComponent];
}
NSInteger groupRow = [vehiclePicker selectedRowInComponent:kGroupComponent];
NSInteger vehicleRow = [vehiclePicker selectedRowInComponent:kListComponent];
NSString *group = [self.groupOfVehicles objectAtIndex:groupRow];
NSString *vehicle = [self.listVehicles objectAtIndex:vehicleRow];
groupLabel.text = [[NSString alloc] initWithFormat: #"%#", group];
vehicleLabel.text = [[NSString alloc] initWithFormat: #"%#", vehicle];
valueForOtherView = vehicleLabel.text;}
Here what I want to know is that what if user selects a single vehicle from the picker view then all other pin views/ locations should be hidden/removed from the view and the only selected location/ pin view should be shown.
How can I do that in this picker view didSelectRow method: ?
What I'm doing in a case similar to yours, is:
1) remove first all the annotations
for (id <MKAnnotation> anAnnotation in [NSArray arrayWithArray:mapView_.annotations]) {
[mapView_ removeAnnotation:anAnnotation];
}
2) and then paint the ones selected:
[mapView_ addAnnotation:myAnnotation];

How to update Mapview Periodically?

In my application i want to update the MapView periodically and redraw the the path on map as per new location.
Is it possible using MKMapView?
This is my didload metho for drawing and annotation on mapview.
- (void)viewDidLoad
{
NSString *url=[NSString stringWithFormat:#"xxxxx.php?uid=%#&buddy_uid=%#",UserUID,buddyUid];
NSLog(#"%#",url);
NSLog(#"%#",url);
NSString * jsonString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"return data %#",jsonString);
NSDictionary *jsonDic = [jsonString JSONValue];
buddyLocation = [[NSString alloc] initWithFormat:#"%#,%#",[jsonDic objectForKey:#"Lattitude"],[jsonDic objectForKey:#"Longitude"]];
[super viewDidLoad];
locmanager = [[CLLocationManager alloc] init];
[locmanager setDelegate:self];
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];
//[locmanager startUpdatingLocation];
MKMapView *mapnew;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
mapnew = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 768, 1004)];
}
else
{
mapnew = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
}
[mapnew setDelegate:self];
[self.view addSubview:mapnew];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = lat1 floatValue];//22.56574;
region.center.longitude =lng1 floatValue];//73.74575;
NSString *currentLocation = [[NSString alloc] initWithFormat:#"%#,%#",lat1,lng1];
NSLog(#"%#",currentLocation);
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = #"Current Location";
ann.coordinate = region.center;
[mapnew addAnnotation:ann];
NSLog(#"%#",jsonDic);
region.center.latitude = [[jsonDic objectForKey:#"Lattitude"] floatValue];//23.56574;
region.center.longitude = [[jsonDic objectForKey:#"Longitude"] floatValue];//72.74575;
ann = [[DisplayMap alloc] init];
ann.title = #"Buddy Location";
ann.coordinate = region.center;
[mapnew addAnnotation:ann];
KMLParser *kml = [KMLParser parseKMLAtURL:[NSURL URLWithString:[NSString
stringWithFormat:#"https://maps.google.com/maps?saddr=%#&daddr=%#&
output=kml",currentLocation,buddyLocation]]];
NSArray *overlays = [kml overlays];
[mapnew addOverlays:overlays];
MKMapRect flyTo = MKMapRectNull;
for (id <MKOverlay> overlay in overlays)
{
if (MKMapRectIsNull(flyTo))
{
flyTo = [overlay boundingMapRect];
}
else
{
flyTo = MKMapRectUnion(flyTo, [overlay boundingMapRect]);
}
}
mapnew.visibleMapRect = flyTo;
[mapnew release];
mapnew =nil;
}
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView *line = [[[MKPolylineView alloc] initWithPolyline:overlay] autorelease];
line.strokeColor = [UIColor blueColor];
line.lineWidth =2.0;
return line;
}
ViewDidiLoad method is called only once when the view is loaded After that it would only give control to methods like viewWillappear etc on successive visits . What you have to do is seperate the method which parses the location data from viewDidLoad, and make it set an array or objects . And call the method to reset these contents on Map i.e. remove previous annotations or overlay and then add new ones . problem solved. You could call these method at fixed interval using timer or something like that. I guess this should help.

viewForAnnotation Not Called Until Map is Moved

viewForAnnotation is not being called until I move or zoom in on the map. Because of this, my annotations do not show until the map is touched. Any idea why?
NSString *incident;
for (incident in weekFeed) {
NSString *finalCoordinates = [[NSString alloc] initWithFormat:#"%#", [incident valueForKey:#"coordinates"]];
NSArray *coordinatesArray = [finalCoordinates componentsSeparatedByString:#","];
latcoord = (#"%#", [coordinatesArray objectAtIndex:0]);
longcoord = (#"%#", [coordinatesArray objectAtIndex:1]);
// Final Logs
NSLog(#"Coordinates in NSString: [%#] - [%#]", latcoord, longcoord);
CLLocationCoordinate2D coord;
coord.latitude = [latcoord doubleValue];
coord.longitude = [longcoord doubleValue];
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [incident valueForKey:#"incident_type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [incident valueForKey:#"note"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
[ann release];
}
// Custom Map Markers
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil; //return nil to use default blue dot view
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.canShowCallout = YES;
if ([annotationView.annotation.title isEqualToString:#"one"]) {
UIImage *pinImage = [UIImage imageNamed:#"marker_1.png"];
[annotationView setImage:pinImage];
}
if ([annotationView.annotation.title isEqualToString:#"two"]) {
UIImage *pinImage = [UIImage imageNamed:#"marker_2.png"];
[annotationView setImage:pinImage];
}
annotationView.annotation = annotation;
return annotationView;
}
- (void) mapView:(MKMapView *)mapV didAddAnnotationViews:(NSArray *)views {
CGRect visibleRect = [mapV annotationVisibleRect];
for (MKAnnotationView *view in views) {
CGRect endFrame = view.frame;
CGRect startFrame = endFrame; startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
view.frame = startFrame;
[UIView beginAnimations:#"drop" context:NULL];
[UIView setAnimationDuration:0.4];
view.frame = endFrame;
[UIView commitAnimations];
}
}
I solved it by using [self performSelectorInBackground:#selector(loadEverything) withObject:self]; instead of detachThreadSelector. That code (in viewDidLoad) wasn't originally posted.
Thanks for helping everyone!

IPhone SDK MapKIt Multiple Points and Annotation

I am new to IPhone SDK Development i am trying to make an application with MapKit i have done the first bit i want to add multiple pins and annotation to the application but i am lost here.
Following is the code how can i add more pins to this code
-(void)viewDidLoad{
[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
MKCoordinateRegion region={{0.0,0.0,},{0.0,0.0}};
region.center.latitude = 26.438047;
region.center.longitude = 50.116422;
region.span.latitudeDelta=0.01f;
region.span.longitudeDelta=0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = #"Corporate Office";
ann.subtitle =#"King Khalid Street";
ann.coordinate=region.center;
[mapView addAnnotation:ann];
}
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>) annotation{
MKPinAnnotationView *pinView=nil;
if (annotation != mapView.userLocation) {
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if (pinView ==nil) pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor=MKPinAnnotationColorRed;
pinView.canShowCallout=YES;
pinView.animatesDrop=YES;
pinView.calloutOffset= CGPointMake(-5, 5);
}
else {
[mapView.userLocation setTitle:"I am here"];
}
return pinView;
}
you are on the right track already, just reuse your code to make multiple points.
for example :
DisplayMap *ann = [[DisplayMap alloc] init];
for( int i =1;i<=5;i++ ){
region.center.latitude = 26.438047+i;
region.center.longitude = 50.116422+i;
ann.title = [NSString stringWithFormat:#"title %d",i)];
ann.subtitle =[NSString stringWithFormat:#"subtitle %d",i)];
ann.image = [NSString stringWithFormat#"image_%d.png",i];
ann.coordinate=region.center;
[mapView addAnnotation:ann];
}
[ann release];
in result, will display 5 points in different coordinate. (with same name and subtitle).
Edited: show different pin image. you have to add new field as NSString *image to DisplayMap. and add your path image inside for loop.
- (MKAnnotationView *) mapView:(MKMapView *)amapView viewForAnnotation:(id <MKAnnotation>) annotation
{
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 != map.userLocation)
{
static NSString *defaultPinID = #"your-pin";
pinView = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( counting < [map.annotations count])
{
counting++;
pinView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
for(DisplayMap* a in map.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;
}