Google Maps SDK for IOS markers are being overwritten - ios

I am having problems plotting multiple markers with Google Maps SDK for iOS (ver. 1.5.0). I am new to objective c (using Xcode ver 4.6.3) and the Google Maps SDK so I may be missing something obvious. Also I'm using iOS 6.1 simulator. I'm trying to learn by doing.
I have spent several days searching and have found several threads that have dealt with this topic, but none of the solutions work for me. The problem that I'm having is that my markers are overwriting each other. I created an NSArray, locations, that will have 4 columns and unknown rows. The columns are latitude, longitude, name, address.
for(int i=0;i<[locations count];i++){
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:40.0823
longitude:-74.2234
zoom:7];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView_;
mapView_.myLocationEnabled = YES;
mapView_.mapType = kGMSTypeHybrid;
mapView_.settings.myLocationButton = YES;
mapView_.settings.zoomGestures = YES;
mapView_.settings.tiltGestures = NO;
mapView_.settings.rotateGestures = NO;
NSString *lat = [[locations objectAtIndex:i] objectAtIndex:0];
NSString *lon = [[locations objectAtIndex:i] objectAtIndex:1];
double lt=[lat doubleValue];
double ln=[lon doubleValue];
NSString *name = [[locations objectAtIndex:i] objectAtIndex:2];
NSMutableArray *markersArray = [[NSMutableArray alloc] init];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.appearAnimation=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = [[locations objectAtIndex:i] objectAtIndex:3];
marker.map = mapView_;
[markersArray addObject:marker];
}

I see something wrong that's possibly related. You're overwriting markersArray every time you iterate through the locations array in the for loop. Instantiate markersArray outside of the for loop.
Could you try to NSLog the coordinates of each marker you're trying to plot?
If the coordinates are the same, the marker should plot right on top of each other making it appear that markers are being overridden, but they're just on top of each other.
Log the count of the locations and markersArray after you're done to make sure they're equal to each as a quick check.
*Edit: I see your problem. You're overriding your MapView every time you iterate through your for loop.
Try something like this:
// Create a markersArray property
#property (nonatomic, strong) NSMutableArray *markersArray;
// Create a GMSMapView property
#property (nonatomic, strong) GMSMapView *mapView_;
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupMapView];
[self plotMarkers];
}
// Lazy load the getter method
- (NSMutableArray *)markersArray
{
if (!_markersArray) {
_markersArray = [NSMutableArray array];
}
return _markersArray;
}
- (void)setupMapView
{
self.mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = self.mapView_;
self.mapView_.myLocationEnabled = YES;
self.mapView_.mapType = kGMSTypeHybrid;
self.mapView_.settings.myLocationButton = YES;
self.mapView_.settings.zoomGestures = YES;
self.mapView_.settings.tiltGestures = NO;
self.mapView_.settings.rotateGestures = NO;
// You also instantiate a GMSCameraPosition class, but you don't add it to your mapview
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:40.0823
longitude:-74.2234
zoom:7];
}
- (void)plotMarkers
{
// I don't know how you're creating your locations array, so I'm just pretending
// an array will be returned from this fake method
NSArray *locations = [self loadLocations];
for (int i=0; i<[locations count]; i++){
NSString *lat = [[locations objectAtIndex:i] objectAtIndex:0];
NSString *lon = [[locations objectAtIndex:i] objectAtIndex:1];
double lt=[lat doubleValue];
double ln=[lon doubleValue];
NSString *name = [[locations objectAtIndex:i] objectAtIndex:2];
// Instantiate and set the GMSMarker properties
GMSMarker *marker = [[GMSMarker alloc] init];
marker.appearAnimation=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = [[locations objectAtIndex:i] objectAtIndex:3];
marker.map = self.mapView_;
[self.markersArray addObject:marker];
}
}

Related

Multiple marker is not showing

I want to show multiple marker on google map. There are answers based on this. But markers are not showing on the map. Although I am getting the latitude and longitude value based on the array result. What should I do?
Note: I have done some changes and the code running perfectly.
My code is:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self performRequestForRestaurantListing];
geometryDict=[[NSMutableDictionary alloc]init];
locationDict=[[NSMutableDictionary alloc]init];
NSLog(#"the value of list is %#", _service);
NSLog(#"the value of stringradius is %#", _stringRadius);
/*---location Manager Initialize-------*/
self.manager=[[CLLocationManager alloc]init];
self.manager.distanceFilter = 100;
self.manager.desiredAccuracy = kCLLocationAccuracyBest;
[self.manager requestAlwaysAuthorization];
self.manager.delegate=self;
[self.manager startUpdatingLocation];
[mapView setDelegate:self];
latitude=#"22.5726";
longitude=#"88.3639";
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[latitude doubleValue]
longitude:[longitude doubleValue]
zoom:12];
[mapView animateToCameraPosition:camera];
[self coordinateOnMap:latitude andWithLongitude:longitude];
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude
{
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] init];
CLLocationCoordinate2D location;
for (int i=0;i<[restaurantList count];i++)
{
driverMarker = [[GMSMarker alloc] init];
latitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lat"];
longitude=[[[[restaurantList objectAtIndex:i]objectForKey:#"geometry"]objectForKey:#"location"] objectForKey:#"lng"];
location.latitude = [latitude floatValue];
location.longitude = [longitude floatValue];
driverMarker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude);
driverMarker.map = mapView;
}
driverMarker.icon=[UIImage imageNamed:#"marker"];
bounds = [bounds includingCoordinate:driverMarker.position];
driverMarker.title = #"My locations";
[driverMarker setTappable:NO];
mapView.myLocationEnabled = YES;
}
I guess your driveMarker gets deallocated by ARC immediatly after each loop.
If this really is your issue, you'll have to make sure that those markers "survive" the loop, e.g. with the following code:
#implementation MyController
#property (nonatomic) NSMutableArray *allMarkers;
- (void)viewDidLoad {
allMarkers = [[NSMutableArray alloc] init];
// ...
}
-(void)coordinateOnMap:(NSString*)latitude andWithLongitude:(NSString*)longitude {
//...
[allMarkers removeAllObjects];
for (int i=0;i<[restaurantList count];i++) {
GMSMarker *driverMarker = [[GMSMarker alloc] init];
[allMarkers addObject:driveMarker];
// ...
}
}
#end
This will create an NSArray property to store all created markers, just to keep them in scope.

How to Remove All markers from googlemap not mapview.clear (ios objective-c)

I am trying to remove existing all markers from google maps, we can do by map.clear but I don't want to remove everything(Polyline, polygons) on map, I just want to remove only markers
I am creating markers based on array count
-(void)annotationCreationForCoordinatesOfArray:(NSMutableArray *)array
{
for (int i=0; i<array.count; i++)
{
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[[array objectAtIndex:i] objectForKey:#"latitude"] doubleValue], [[[array objectAtIndex:i] objectForKey:#"longitude"] doubleValue]);
mark = [GMSMarker markerWithPosition:position];
NSString *annoNumber = [NSString stringWithFormat:#"%i",i];
mark.title = annoNumber;
mark.map = _mapView;
mark.tracksViewChanges = YES;
mark.draggable = YES;
mark.icon = [UIImage imageNamed:#"Mappin.png"];
}
}
Try this code its work for me.
Create global array
NSMutableArray *removalMarkerArray;
Now add all marker in global array
removalMarkerArray=[[NSMutableArray alloc]init];
-(void)annotationCreationForCoordinatesOfArray:(NSMutableArray *)array{
for (int i=0; i<array.count; i++){
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[[array objectAtIndex:i] objectForKey:#"latitude"] doubleValue], [[[array objectAtIndex:i] objectForKey:#"longitude"] doubleValue]);
mark = [GMSMarker markerWithPosition:position];
NSString *annoNumber = [NSString stringWithFormat:#"%i",i];
mark.title = annoNumber;
mark.map = _mapView;
mark.tracksViewChanges = YES;
mark.draggable = YES;
mark.icon = [UIImage imageNamed:#"Mappin.png"];
[removalMarkerArray addObject:mark];
}
}
Then where you want to clear all marker
for (GMSMarker *marker in removalMarkerArray ){
marker.map = nil;
}

fitBounds in GoogleMaps SDK for ios does not fit

I want use fitBounds method in GoogleMaps for ios SDK and view does not fit. My varaibles are all right (path, arrays, etc...) because I can see polyline with markers on map. The only thing that does not work is fit to view. Where I have made mistake? thank you.
// Create a 'normal' polyline.
GMSPolyline *polyline = [[GMSPolyline alloc] init];
GMSMutablePath *path = [GMSMutablePath path];
locationInfoArray = [LocationInfoMemoryManager loadLocationDataWithPath:_locationInfoPathString];
for (int i=0; i<locationInfoArray.count; i++) {
LocationInfo* locationInfo = locationInfoArray[i];
CLLocationCoordinate2D locationPoint = {locationInfo.latitude, locationInfo.longitude};
[path addCoordinate:locationPoint];
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:[locationInfoArray[0] latitude]
longitude:[locationInfoArray[0] longitude]
zoom:5 ];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
polyline.path = path;
polyline.strokeColor = [UIColor blueColor];
polyline.strokeWidth = 10.f;
polyline.zIndex = 15; // above the larger geodesic line
polyline.map = mapView;
GMSMarker *startMarker = [[GMSMarker alloc] init];
startMarker.title = #"Start";
startMarker.snippet = #"Info will be here";
startMarker.position = CLLocationCoordinate2DMake([[locationInfoArray firstObject] latitude], [[locationInfoArray firstObject] longitude]);
startMarker.map = mapView;
startMarker.flat = NO;
//sydneyMarker.rotation = 30.0;
mapView.selectedMarker = startMarker;
GMSMarker *finishMarker = [[GMSMarker alloc] init];
finishMarker.title = #"Finish";
finishMarker.snippet = #"Info will be here";
finishMarker.position = CLLocationCoordinate2DMake([[locationInfoArray lastObject] latitude], [[locationInfoArray lastObject] longitude]);
finishMarker.map = mapView;
finishMarker.flat = NO;
mapView.selectedMarker = finishMarker;
//Here is probably problem
GMSCoordinateBounds *bounds; = [[GMSCoordinateBounds alloc] initWithPath:path];
GMSCameraUpdate *update = [GMSCameraUpdate fitBounds:bounds withPadding:20];
[mapView moveCamera:update];
self.view = mapView;
Is this code in loadView or viewDidLoad? Based on these earlier questions, I think camera updates only work correctly from viewWillAppear:
GMSCameraUpdate zooming out to the max distance rather than around a path
Fit bounds not working as expected

Google Maps iOS API markers not clearing or creating new markers

I have been working with the Google Maps API for iOS, and I am trying to recreate the positions of markers after getting an array of new positions/locations.
Here is my code for the Google Maps:
- (void)loadView {
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:locationManager.location.coordinate.latitude
longitude:locationManager.location.coordinate.longitude zoom:13.2];
mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView.delegate = self;
self.view = mapView;
[mapView clear];
[self createMarker];
}
- (void) createMarker {
NSLog(#"createmarkers called");
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSMutableArray *lat = [[NSMutableArray alloc]init];
NSMutableArray *lng = [[NSMutableArray alloc]init];
NSMutableArray *markers = [[NSMutableArray alloc]init];
NSMutableArray *businessArray = [[NSMutableArray alloc]init];
for (int x = 0; x < [appDelegate.businessArray count]; x++){
[businessArray addObject: [appDelegate.businessArray objectAtIndex:x] ];
}
for (int x = 0; x < [appDelegate.geocodedLatArrayGlobal count]; x++){
NSNumber *latCoord = [NSNumber numberWithDouble:[[appDelegate.geocodedLatArrayGlobal objectAtIndex:x]doubleValue]];
[lat addObject: latCoord];
}
for (int x = 0; x < [appDelegate.geocodedLngArrayGlobal count]; x++){
NSNumber *lngCoord = [NSNumber numberWithDouble:[[appDelegate.geocodedLngArrayGlobal objectAtIndex:x]doubleValue]];
[lng addObject:lngCoord];
}
for (int x = 0; x < [businessArray count]; x++){
double latitude =[[lat objectAtIndex:x]doubleValue];
double longitude =[[lng objectAtIndex:x]doubleValue];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitude,longitude) ;
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.title = [[businessArray objectAtIndex:x]valueForKey:#"name"];
marker.snippet = #"123";
marker.icon = [UIImage imageNamed:#"greenPin.png"];
marker.animated = YES;
marker.map = mapView;
[markers addObject:marker];
}
}
If I load the view for the first time, the markers are being created. However, the second time with a new set/array of lat/long coordinates does not load.
The loadview method is being called, and the [mapView clear]; should be called, but it isn't clearing the markers on the mapview. The next problem is that the new markers are not being created, but I suspect that both these problems have to do with the same thing.
Any tips on why the map view won't clear? Thanks in advance

adding multiple pins on google map in ios

I want to add multiple pins on a google map, while it is being loaded.
I have a list of Latitude and Longitude values of nearby locations.
How can I show all these locations on the map with a pin. I am using Google SDK for iOS.
I am using the following code, but it didn't work for me.
NSMutableArray *array = [NSMutableArray arrayWithObjects:#"12.981902,80.266333",#"12.982902,80.266363", nil];
CLLocationCoordinate2D pointsToUse[5];
for (int i = 0; i < [array Size]; i++)
{
pointsToUse[i] = CLLocationCoordinate2DMake([[[[array objectAtIndex:0] componentsSeparatedByString:#","] objectAtIndex:0] floatValue],[[[[array objectAtIndex:0] componentsSeparatedByString:#","] objectAtIndex:1] floatValue]);
[array removeObjectAtIndex:0];
GMSMarkerOptions *options = [[GMSMarkerOptions alloc] init];
options.position = pointsToUse[i];
[mapView_ animateToLocation:pointsToUse[i]];
[mapView_ addMarkerWithOptions:options];
}
I have tried enough to search for it but there isn't enough documentation to answer my question.
Thanks in advance for the help.
This works for me:
for(GMSMarker*marker in array)
{
GMSMarker *mkr= [[GMSMarker alloc]init];
[mkr setPosition:CLLocationCoordinate2DMake(<coord>)];
[mkr setAnimated:YES];
[mkr setTitle:<Title>];
[mkr setSnippet:<Snippet>];
[mkr setMap:mapView_];
}
Using latest Google Maps SDK.
Hope it helps
self.view = mapView_;
for(int i=0;i<[array count];i++)
{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.animated=YES;
marker.position = CLLocationCoordinate2DMake(latitude,longitude);
marker.title = #"name";
marker.snippet = #"snippet";
marker.map = mapView_;
}
This worked for me!
For swift we can use
for i in 0..<array.count() {
var marker = GMSMarker()
marker.animated = true
marker.position = CLLocationCoordinate2DMake(latitude, longitude)
marker.title = "name"
marker.snippet = "snippet"
marker.map = mapView_
}

Resources