Draw a line in multiple pins in the map - iphone

I want to set pin in multiple addresses or location in the map and then draw a line among this pin-point. Pins and Line will show in the map . i find a code , that only show pin of some location .. here is my code . .
- (void)viewDidLoad {
[super viewDidLoad];
mapView.delegate=self;
NSMutableArray* annotations=[[NSMutableArray alloc] init];
for (int i =1; i <=10; i++) {
CLLocationCoordinate2D theCoordinate1;
if (i==1) {
theCoordinate1.latitude = 37.786996;
theCoordinate1.longitude = -122.419281;
}
if (i==2) {
theCoordinate1.latitude = 37.810000;
theCoordinate1.longitude = -122.477989;;
}
if (i==3) {
theCoordinate1.latitude = 37.80000;
theCoordinate1.longitude = -122.407989;
}
if (i==4) {
theCoordinate1.latitude = 37.82000;
theCoordinate1.longitude = -122.407989;
}
MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];
myAnnotation1.coordinate=theCoordinate1;
[mapView addAnnotation:myAnnotation1];
[annotations addObject:myAnnotation1];
}
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
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;
}
i want to draw a line among this points of . and finally it looks like a path , and pins are standing on this path or line .
thank you advance .

for example
CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(31.484137685, 120.371875243);
CLLocationCoordinate2D coord2 = CLLocationCoordinate2DMake(31.484044745, 120.371879653);
points[0] = MKMapPointForCoordinate(coord1);
points[1] = MKMapPointForCoordinate(coord2);
MKPolyline *line = [MKPolyline polylineWithPoints:points count:2];
[myMap addOverlay: line];
and you shuold add this code below.
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay{
if ([overlay isKindOfClass:[MKPolyline class]])
{
MKPolylineView *lineview=[[[MKPolylineView alloc] initWithOverlay:overlay] autorelease];
lineview.strokeColor=[[UIColor blueColor] colorWithAlphaComponent:0.5];
lineview.lineWidth=2.0;
[arr release];
return lineview;
}
}

Related

Core plot : bars disappears when switching app to background and then to foreground while drawing a bar graph

My bar graph disappears when I switch my app to background and then again comes back to foreground.
It's like shown below :
||| || ||
So in the above picture I have gaps, that means when my app is in background core plot does not draw bar graph. Is it a limitation of core plot?
My main task is to draw one bar per second and I have done this, but it's not working while in background. Is there some other alternate option by which I can achieve this?
Here is what I tried:
I made my graph object nil and then tried it reloading when app again comes back to foreground. But it didn't work.
-(void)redrawGraphWhenApplicationEntersForeground
{
NSLog(#"reload graph");
NSLog(#"all plots : %# , %#", [self.graph allPlots], plotArray);
DDLogInfo(#"relaod graph when entered in Foreground ");
// [self.data removeAllObjects];
//Create graph and set it as host view's graph
self.graph = nil;
[self.graph reloadDataIfNeeded];
}`
Here is my full code :
// Update is called by a timer ( of 10 second) , so that each second this method will be called and it will draw a bar.
- (void)update:(id)data1 withState:(NSInteger) type
{
switch (type) {
case ZAP_UPDATE:
if(curLinkType == DOWNLINK)
{
[self drawDownlinkGrpah];
}else if(curLinkType == UPLINK)
{
[self drawUplinkGrpah];
}
[gauge setValue:speedValue];
break;
case ZAP_DONE:
[self displayDone:type speedBps:speedBps pktLoss:pktLoss srcdst:[zap destinationAddress]];
onTap = false;
runningTime=0;
if(gauge != nil){
[gauge setValue:0];
}
{
NSArray *parameter = [NSArray arrayWithObjects: speed, unit, nil];
[self performSelector:#selector(stopGauge:) withObject:parameter afterDelay:0.2];
}
}
}
- (void)drawDownlinkGrpah {
DownlinCount++;
self.downlinkdata = [NSMutableArray array];
double position = DownlinCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.downlinkdata addObject:bar];
self.data = self.downlinkdata;
[self generateBarPlotForDownlink:YES];
}
- (void)drawUplinkGrpah {
UplinkCount++;
self.uplinkdata = [NSMutableArray array];
double position = UplinkCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.uplinkdata addObject:bar];
self.data = self.uplinkdata;
[self generateBarPlotForDownlink:NO];
}
- (NSInteger)getBarposition:(NSInteger)samplesize {
return (4*10)/samplesize;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)resetGraph:(UIImageView*) imageview {
for(UIView *view in imageview.subviews)
[view removeFromSuperview];
[imageview setImage:[UIImage imageNamed:#"graph_container"]];
}
#pragma mark -
-(void)appGoesinBackground
{
// NSLog(#"make nil graph");
// DDLogInfo(#"remove graph when entered in background ");
//
self.graph = nil;
// [self.data removeAllObjects];
[plotArray removeAllObjects]; // remove all data before entering to background
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(redrawGraphWhenApplicationEntersForeground)
name: UIApplicationDidBecomeActiveNotification
object: nil];
}
// redraw graph ..
-(void)redrawGraphWhenApplicationEntersForeground
{
NSLog(#"reload graph");
NSLog(#"all plots : %# , %#", [self.graph allPlots], plotArray);
DDLogInfo(#"relaod graph when entered in Foreground ");
// [self.data removeAllObjects];
//Create graph and set it as host view's graph
// self.graph = nil;
//
for (CPTBarPlot *p in plotArray) {
// [self.graph addPlot:p];
[p reloadData];
}
}
#pragma mark - generate bar plot
- (void)generateBarPlotForDownlink:(BOOL)enabled
{
NSLog(#"generateBarPlotForDownlink >>>>>>");
//Create host view
self.hostingView = [[CPTGraphHostingView alloc] initWithFrame:CGRectMake(-35, -20, 128, 73)];
//Create graph and set it as host view's graph
self.graph = [[CPTXYGraph alloc] initWithFrame:self.downlinkImageView.frame];
self.graph.plotAreaFrame.masksToBorder = NO;
[self.hostingView setHostedGraph:self.graph];
if(enabled) // for downlink graph ..
{
self.downlinkImageView.image=nil;
[self.downlinkImageView addSubview:self.hostingView];
}
else{ // for uplink graph ..
self.uplinkImageView.image=nil;
[self.uplinkImageView addSubview:self.hostingView];
}
// Create bar plot and add it to the graph
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat(maxYRange)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.xAxis.minorTickLength = 1.0f;
axisSet.yAxis.minorTickLength = 1.0f;
axisSet.hidden=YES;
axisSet.xAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
axisSet.yAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
float barwidht = (2*10.0)/(float)durationval;
NSString *inStr = [NSString stringWithFormat: #"%f", barwidht];
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:inStr] // Need to change according sample // 1.5 for 10 , 0.75 for 20
decimalValue];
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barCornerRadius = 0.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
// Add plot to array in case if app is moved to background state ..
[plotArray addObject:plot];
NSLog(#"plot : %#",plot);
NSLog(#"plot added ..%lu", (unsigned long)plotArray.count );
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTBarPlotFieldBarLocation)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTBarPlotFieldBarTip)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
-(CPTFill *)barFillForBarPlot:(CPTBarPlot *)barPlot
recordIndex:(NSUInteger)index
{
if ( [barPlot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
CPTGradient *gradient = [CPTGradient gradientWithBeginningColor:[CPTColor redColor]
endingColor:[bar valueForKey:#"COLOR"]
beginningPosition:0.0 endingPosition:0.6 ];
[gradient setGradientType:CPTGradientTypeAxial];
[gradient setAngle:320.0];
CPTFill *fill = [CPTFill fillWithGradient:gradient];
return fill;
}
return [CPTFill fillWithColor:[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
}
Screenshot:
You don't need to create a new graph every time you get new plot data. Just add the new point to the data array and call -reloadData on the plot.
When the app goes into the background, just clear your data array and call -reloadData on the plot. It will reload the empty data and display the graph when the app comes back to the foreground. There's no reason to set self.graph to nil unless you remove the graph from the hosting view and you want it to go away. From what I can see in the posted code, the graph is still in the hosting view, but you've lost your reference to it, making any updates you make when the app comes to the foreground ineffective.
Here is the code that worked for me :
- (void)drawDownlinkGrpah {
NSLog(#"drawDownlinkGrpah CAlled");
DownlinCount++;
double position = DownlinCount*((4*10)/(double)durationval);
NSDictionary *bar = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:position],BAR_POSITION,
[NSNumber numberWithDouble:speedBarValue],BAR_HEIGHT,
[UIColor orangeColor],COLOR,
nil];
[self.downlinkdata addObject:bar];
self.data = self.downlinkdata;
[self generateBarPlotForDownlink:YES];
}
#pragma mark - generate bar
- (void)generateBarPlotForDownlink:(BOOL)enabled
{
if(enabled)
{
self.downlinkImageView.image=nil;
if(![self.hostingView isDescendantOfView:self.downlinkImageView])
{
// Configure hosting view so that it appears from fresh ..
[self configureGraph];
[self.downlinkImageView addSubview:self.hostingView];
NSLog(#"hosting view added in downlink view ");
}
}
else
{
self.uplinkImageView.image=nil;
// if hosting view is not in uplink view
if(![self.hostingView isDescendantOfView:self.uplinkImageView])
{
// Configure hosting view so that it appears from fresh ..
[self configureGraph];
[self.uplinkImageView addSubview:self.hostingView];
NSLog(#"hosting view added in uplink view ");
}
}
//set axes ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat((AXIS_END - AXIS_START)+1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:
CPTDecimalFromFloat(AXIS_START)
length:CPTDecimalFromFloat(maxYRange)];
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
axisSet.xAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(1.0f);
axisSet.xAxis.minorTickLength = 1.0f;
axisSet.yAxis.minorTickLength = 1.0f;
axisSet.hidden=YES;
axisSet.xAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
axisSet.yAxis.labelingPolicy=CPTAxisLabelingPolicyNone;
// Create bar plot and add it to the graph
NSLog(#"plot created %ld", (long)durationval);
CPTBarPlot *plot = [[CPTBarPlot alloc] init] ;
plot.dataSource = self;
plot.delegate = self;
float barwidht = (2*10.0)/(float)durationval;
NSString *inStr = [NSString stringWithFormat: #"%f", barwidht]; //CPTDecimalFromDouble(2.0);
plot.barWidth = [[NSDecimalNumber decimalNumberWithString:inStr]
decimalValue];// Need to change according sample // 1.5 for 10 , 0.75 for 20
plot.barWidth = CPTDecimalFromDouble(barwidht);
plot.barOffset = [[NSDecimalNumber decimalNumberWithString:#"5.0"]
decimalValue];
plot.barCornerRadius = 0.0;
// Remove bar outlines
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor clearColor];
plot.lineStyle = borderLineStyle;
plot.identifier = #"chocoplot";
[self.graph addPlot:plot];
}
#pragma mark - core plot data source and delegate methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot.identifier isEqual:#"chocoplot"] )
return [self.data count];
return 0;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
if ( [plot.identifier isEqual:#"chocoplot"] )
{
NSDictionary *bar = [self.data objectAtIndex:index];
if(fieldEnum == CPTScatterPlotFieldX)
return [bar valueForKey:BAR_POSITION];
else if(fieldEnum ==CPTScatterPlotFieldY)
return [bar valueForKey:BAR_HEIGHT];
}
return [NSNumber numberWithFloat:0];
}
drawDownlinkGraph method would be called each second using a timer and it will call generateBarPlotForDownlink: Method every second . And bar will be drawn each second on a real time basis even if APP is in background.

UIMapView shows wrong region sometimes

When I show UIViewController with UIMapView, in viewDidLoad I add PointAnnotation to map and to array. Then I calculate the region for these annotations and set that region to map.
The point is that sometimes (basically only once after installing app for the first time) the map shows region for equator even if my data is correct.
-(void)viewDidLoad
{
NSLog(#"Spot: %#", _spot);
_annotations = [[NSMutableArray alloc] init];
[super viewDidLoad];
// Adding annotation of spot
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = self.spot.latitude;
annotationCoord.longitude = self.spot.longitude;
POPointAnnotation *annotationPoint = [[POPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = self.spot.name;
annotationPoint.subtitle = self.spot.address;
annotationPoint.type = PointAnnotaitonTypeSpot;
[_annotations addObject:annotationPoint];
[((SpotsMapView *)self.view).mapView addAnnotation:annotationPoint];
[annotationPoint release];
// Adding annotation of user position
CLLocationCoordinate2D userCoord;
userCoord = [[POLocationManager sharedInstance] location].coordinate;
POPointAnnotation *userPoint = [[POPointAnnotation alloc] init];
userPoint.coordinate = userCoord;
userPoint.title = NSLocalizedString(#"Punkt startowy", #"Punkt startowy");
userPoint.type = PointAnnotationTypeStart;
[_annotations addObject:userPoint];
[((SpotsMapView *)self.view).mapView addAnnotation:userPoint];
[userPoint release];
[((SpotsMapView *)self.view).mapView setRegion:[self regionFromLocations] animated:YES];
[((SpotsMapView *)self.view).mapView setShowsUserLocation:YES];
}
and region here:
- (MKCoordinateRegion)regionFromLocations {
CLLocationCoordinate2D upper = [[self.annotations objectAtIndex:1] coordinate];
CLLocationCoordinate2D lower = [[self.annotations objectAtIndex:1] coordinate];
NSLog(#"Loc Upper: %f, %f", upper.latitude, upper.longitude);
NSLog(#"Loc Lower: %f, %f", lower.latitude, lower.longitude);
// FIND LIMITS
for(MKPointAnnotation *eachLocation in self.annotations) {
if([eachLocation coordinate].latitude > upper.latitude) upper.latitude = [eachLocation coordinate].latitude;
if([eachLocation coordinate].latitude < lower.latitude) lower.latitude = [eachLocation coordinate].latitude;
if([eachLocation coordinate].longitude > upper.longitude) upper.longitude = [eachLocation coordinate].longitude;
if([eachLocation coordinate].longitude < lower.longitude) lower.longitude = [eachLocation coordinate].longitude;
}
NSLog(#"Loc Upper: %f, %f", upper.latitude, upper.longitude);
NSLog(#"Loc Lower: %f, %f", lower.latitude, lower.longitude);
// FIND REGION
MKCoordinateSpan locationSpan;
locationSpan.latitudeDelta = upper.latitude - lower.latitude + 0.003;
locationSpan.longitudeDelta = upper.longitude - lower.longitude+ 0.003;
CLLocationCoordinate2D locationCenter;
locationCenter.latitude = (upper.latitude + lower.latitude) / 2;
locationCenter.longitude = (upper.longitude + lower.longitude) / 2;
MKCoordinateRegion region = MKCoordinateRegionMake(locationCenter, locationSpan);
return region;
}
Once after installing app I get this:
and after that I get this view:
Any idea what can be wrong?

Google Maps markers not removing iOS

I'm running a thread to fetch drivers location every 10 seconds and want to remove the added markers from the map but it doesn't work..
My code:
-(void)APiResponse:(id)returnJson
{
[googleMapsDriverPin setMap:nil];
googleMapsDriverPin = nil;
NSMutableArray *driverPins = [[NSMutableArray alloc]init];
for (int x = 0; x < [[returnJson valueForKey:#"drivers"] count]; x++) {
CLLocation *driverLocations = [[CLLocation alloc]initWithLatitude:[[[[returnJson valueForKey:#"drivers"] objectAtIndex:x] valueForKey:#"driver_latitude"] doubleValue] longitude:[[[[detail valueForKey:#"drivers"] objectAtIndex:x] valueForKey:#"driver_longitude"] doubleValue]];
[driverPins addObject:driverLocations];
}
for (CLLocation *newLocation in driverPins) {
googleMapsDriverPin = [[GMSMarker alloc] init];
[googleMapsDriverPin setPosition:newLocation.coordinate];
[googleMapsDriverPin setAnimated:YES];
[googleMapsDriverPin setTitle:#"title"];
[googleMapsDriverPin setSnippet:#"snippet"];
[googleMapsDriverPin setIcon:[GMSMarker markerImageWithColor:[UIColor blackColor]]];
[googleMapsDriverPin setMap:googleMaps];
}
}
It just keeps adding and adding every 10 seconds and not removing, please help!
Thanks!
Its a kind of quick and dirty option but if you wanted to go that way GMSMarker has a userData property which you could use to tag the driver pins
- (void)apiResponse:(id)returnJson
{
for (GMSMarker *pin in self.googleMaps.markers) {
if (pin.userData == #"Driver Pin"){
pin.map = nil;
}
}
...
for (CLLocation *newLocation in driverPins) {
googleMapsDriverPin = [[GMSMarker alloc] init];
...
[googleMapsDriverPin setUserData:#"Driver Pin"];
}
}
Update:
[self.googleMapsView clear];
On the based on pin id you can also delete pin.
Here deletePinId integer is for selected pin id.
for(GMSMarker *pin in self.mapView_.markers) {
NSLog(#"pin.userData : %#",pin.userData);
int pinId1 = [[pin.userData valueForKey:#"pin_id"] integerValue];
if(deltePinId == pinId1 ){
pin.map = nil;
}
}
you currently only store ONE marker, but you want to add N markers -- so (as saxon said) you need an array to hold all the pins :)
#interface YouClass
...
#property(nonatomic, retain) NSMutableArray *googleMapsDriverPins;
#end
#implementation YourClass
...
-(void)APiResponse:(id)returnJson
{
for(GMSMarker *pin in self.googleMapsDriverPins) {
pin.map = nil;
}
self.googleMapsDriverPins = nil;
NSMutableArray *driverPins = [[NSMutableArray alloc]init];
for (int x = 0; x < [[returnJson valueForKey:#"drivers"] count]; x++) {
CLLocation *driverLocations = [[CLLocation alloc]initWithLatitude:[[[[returnJson valueForKey:#"drivers"] objectAtIndex:x] valueForKey:#"driver_latitude"] doubleValue] longitude:[[[[detail valueForKey:#"drivers"] objectAtIndex:x] valueForKey:#"driver_longitude"] doubleValue]];
[driverPins addObject:driverLocations];
}
self.googleMapsDriverPins = [NSMutableArray arrayWithCapacity:driverPins.count];
for (CLLocation *newLocation in driverPins) {
GMSMarker *googleMapsDriverPin = [[GMSMarker alloc] init];
[googleMapsDriverPin setPosition:newLocation.coordinate];
[googleMapsDriverPin setAnimated:YES];
[googleMapsDriverPin setTitle:#"title"];
[googleMapsDriverPin setSnippet:#"snippet"];
[googleMapsDriverPin setIcon:[GMSMarker markerImageWithColor:[UIColor blackColor]]];
[googleMapsDriverPin setMap:googleMaps];
[self.googleMapsDriverPins addObject:googleMapsDriverPin];
}
}
#end
It looks like you have a loop adding multiple drivers, each of which assigns to the member variable googleMapsDriverPin. Then next time it removes the googleMapsDriverPin - but that will only be the last pin you added, not all of them.
For this to work you would need to add each marker inside your loop to an array, and then remove all of them from the map on your next update.
In Swift 2:
Create an outlet for your map:
#IBOutlet weak var mapView: GMSMapView!
Create an array to store all markers
var markers = [GMSMarker]()
Create markers like this:
func funcName() {
let position = CLLocationCoordinate2DMake(lat, lon)
let marker = GMSMarker(position: position)
for pin: GMSMarker in self.markers {
if pin.userData as! String == "from" {
pin.map = nil
}
}
marker.icon = UIImage(named: "navigation-red")
marker.userData = "from"
marker.map = self.mapView
self.markers.append(marker)
}
You can set the userData property to anything you want and later on use that string to delete that marker.When the funcName function is executed, all markers with userData as "from" are removed from the map.Let me know if you have any queries.

When i drop multiple pins in map depends on different latitude and longitude values. im getting all pins at one place only

When i drop multiple pins in map depends on different latitude and longitude values. im getting all pins are at one place in map.
I wrote this code for dropping multiple pins .
dealerMapView.mapType = MKMapTypeStandard;
dealerMapView.zoomEnabled =YES;
[dealerMapView setDelegate:nil];
dealerMapView.scrollEnabled = YES;
dealerMapView.showsUserLocation = NO;
CLLocationCoordinate2D location;
for (int i =0; i<[delarsInfoArray count]; i++) {
NSString *lattitudeValue = [[delarsInfoArray objectAtIndex:i]objectForKey:#"LATITUDE" ];
NSString *longitudeValue = [[delarsInfoArray objectAtIndex:i]objectForKey:#"LONGITUDE" ];
CLLocationCoordinate2D pCoordinate ;
pCoordinate.latitude = [lattitudeValue floatValue];
pCoordinate.longitude = [longitudeValue floatValue];
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
region.span = span;
region.center = location;
[dealerMapView setRegion:region animated:YES];
myAnnotation1 = [[MyAnnotation alloc] init];
myAnnotation1.coordinate = location;
myAnnotation1.title = [[delarsInfoArray objectAtIndex:i]objectForKey:#"STORE"];
[dealerMapView addAnnotation:myAnnotation1];
}
Try this code:
MKCoordinateSpan span;
span.latitudeDelta = 0.2;
span.longitudeDelta= 0.2;
if( [delarsInfoArray count] > 0 ){
CLLocationCoordinate2D start;
NSString *lattitudeValue = [[delarsInfoArray objectAtIndex:0]objectForKey:#"LATITUDE" ];
NSString *longitudeValue = [[delarsInfoArray objectAtIndex:j]objectForKey:#"LONGITUDE" ];
// create region, consisting of span and location
MKCoordinateRegion mapRegion;
mapRegion.span = span;
mapRegion.center = start;
//Move the map to our location //
[dealerMapView setRegion:mapRegion animated:YES];
}
// do not show pins and annotations more then 200 in the map at a time.
for (int j = 0; j< ([delarsInfoArray count] < 200?[delarsInfoArray count]:200); j++) {
NSString *lattitudeValue = [[delarsInfoArray objectAtIndex:i]objectForKey:#"LATITUDE"];
NSString *longitudeValue = [[delarsInfoArray objectAtIndex:i]objectForKey:#"LONGITUDE" ];
CLLocationCoordinate2D pinLocation;
if(([lattitudeValue floatValue] != 0) && ([longitudeValue floatValue] != 0) ) {
pinLocation.latitude = [lattitudeValue floatValue];
pinLocation.longitude = [longitudeValue floatValue];
if(pinLocation.latitude !=0 && pinLocation.longitude !=0) {
myAnnotation1 = [[MyAnnotation alloc] init];
myAnnotation1.coordinate = location;
myAnnotation1.title = [[delarsInfoArray objectAtIndex:i] objectForKey: #"STORE"];
[dealerMapView addAnnotation:myAnnotation1];
}
}
}
I hope it helps you!! Best Luck. Cheers!!

cannot add another object into an array containing different objects

Someone please help.
I am a noob here who has just created an array to contain all my polyclinics object. Now I need to add in a user object (patientDetail object) into this array. But no matter how i modify the viewDidLoad method, something just seems not quite right.. i cannot populate all the points.. only when i remove all codes that deal with the user object then it works.. Some1 please take a look at the method below and advise? I need to add in the patientDetail object and populate it with the rest of the polyclinics...
thanks for reading =(
- (void)viewDidLoad {
[super viewDidLoad];
_annotation2 = [[NSMutableArray alloc] init];
CLLocation *userLoc = _mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
_annotations=[[NSMutableArray alloc] init];
_listOfPolyClinics = [[NSMutableArray alloc] init];
PatientDetails *patientDetails = [[PatientDatabase database]
patientDetails:_nric];
for (PolyClinics *polyclinics in [[PatientDatabase database]
polyClinics]){
[_listOfPolyClinics addObject:polyclinics];
}
[_listOfPolyClinics addObject:patientDetails];
for (PolyClinics *polyclinics1 in _listOfPolyClinics){
MyAnnotation* myAnnotation=[[MyAnnotation alloc] init];
if ([polyclinics1 isKindOfClass:[PatientDetails class]]){
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.longitude = patientDetails.longitude;
theCoordinate3.latitude = patientDetails.latitude;
myAnnotation.coordinate = theCoordinate3;
myAnnotation.title = _nric;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",patientDetails.category];
}
else{
CLLocationCoordinate2D theCoordinate;
theCoordinate.longitude = polyclinics1.longtitude;
NSLog(#"Halo");
theCoordinate.latitude = polyclinics1.latitude;
NSLog(#"bye");
//myAnnotation.pinColor = MKPinAnnotationColorPurple;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = polyclinics1.name;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",polyclinics1.telephone];
}
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}
Because you have different classes in your array you can't use for (PolyClinics *polyclinics1 in _listOfPolyClinics)to iterate over the array. Use idinstead, then ask the object of what class it is and then cast it to that class if you have to.
Try to change your second for loop to
for (id polyclinics1 in _listOfPolyClinics){
MyAnnotation* myAnnotation=[[MyAnnotation alloc] init];
if ([polyclinics1 isKindOfClass:[PatientDetails class]]){
CLLocationCoordinate2D theCoordinate3;
theCoordinate3.longitude = patientDetails.longitude;
theCoordinate3.latitude = patientDetails.latitude;
myAnnotation.coordinate = theCoordinate3;
myAnnotation.title = _nric;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",patientDetails.category];
} else {
CLLocationCoordinate2D theCoordinate;
PolyClinics *polyclinic = (PolyClinics *)polyclinics1;
theCoordinate.longitude = polyclinic.longtitude;
NSLog(#"Halo");
theCoordinate.latitude = polyclinic.latitude;
NSLog(#"bye");
//myAnnotation.pinColor = MKPinAnnotationColorPurple;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = polyclinic.name;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",polyclinic.telephone];
}
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}