plot marker on Google Maps iOS from JSON file - ios

I would like to plot markers on Google Maps for iOS, and this by including JSON file that will includes longitude and latitude. I can do it manually in the code, by replacing the values.
The problem is that I don't know how to show new markers on the map from JSON file.
Here is my code :
- (void)addDefaultMarkers {
// Add a custom 'glow' marker around Sydney.
GMSMarker *sydneyMarker = [[GMSMarker alloc] init];
sydneyMarker.title = #"Sydney!";
sydneyMarker.icon = [UIImage imageNamed:#"glow-marker"];
sydneyMarker.position = CLLocationCoordinate2DMake(25.062718, 55.130761);
sydneyMarker.map = mapView_;
GMSMarker *melbourneMarker = [[GMSMarker alloc] init];
melbourneMarker.title = #"Melbourne!";
melbourneMarker.icon = [UIImage imageNamed:#"arrow"];
melbourneMarker.position = CLLocationCoordinate2DMake(25.100822, 55.17467);
melbourneMarker.map = mapView_;
}
Any ideas on how to do it ?

chech my question in this link, stackoverflow.com/questions/20902732/…. This link will help,
First of all parse the json data. And collect it as array or dictionary, then U can directly plot the value in map
The first two lines are to parse the data into an array
SBJsonParser *jsonParser = [SBJsonParser new];
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
then, the loop should continue till the no. of values,
for(int i=0;i<[jsonData count];i++)
{
NSDictionary *dict=(NSDictionary *)[jsonData objectAtIndex:i];
Nslog(#"%#",dict);
double la=[[dict objectForKey:#"latitude"] doubleValue];
double lo=[[dict objectForKey:#"longitude"] doubleValue];
CLLocation * loca=[[CLLocation alloc]initWithLatitude:la longitude:lo];
CLLocationCoordinate2D coordi=loca.coordinate;
marker=[GMSMarker markerWithPosition:coordi];
marker.snippet = #"Hello World";
marker.animated = YES;
marker.map = mapView;
}

Related

Adding annotations from a KML file to an MKMapView

I am trying to load data from a KML file over to an MKMapView. I was able to parse the data into an array and now I am trying to create annotations on the map for each item.
Using the code below, I was able to create annotations on the map but the location is not correct:
Parser *parser = [[Parser alloc] initWithContentsOfURL:url];
parser.rowName = #"Placemark";
parser.elementNames = #[#"name", #"address", #"coordinates", #"description"];
[parser parse];
//parseItem is an array returned with all data after items are parsed.
for (NSDictionary *locationDetails in parser.parseItems) {
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.title = locationDetails[#"name"];
NSArray *coordinates = [locationDetails[#"coordinates"] componentsSeparatedByString:#","];
annotation.coordinate = CLLocationCoordinate2DMake([coordinates[0] floatValue], [coordinates[1] floatValue]);
[self.mapView addAnnotation:annotation];
}
The result of the NSLog of the coordinates was:
coords=-73.96300100000001,40.682846,0
So it looks like the coordinates are coming in longitude,latitude order but the CLLocationCoordinate2DMake function takes latitude,longitude.
Unless the coordinates are supposed to be in Antarctica instead of New York City, try:
annotation.coordinate = CLLocationCoordinate2DMake(
[coordinates[1] doubleValue],
[coordinates[0] doubleValue]);
Also note you should change floatValue to doubleValue for more accurate placement (it will also match the type of CLLocationDegrees which is a synonym for double).

Attempting to drop pins based on MKMap from values from array

As the question says I am trying to add pins to my map based on the coordinates returned by my php file. Said file returns the following results
[{"dogid":"1","latitude":"15.435786","longitude":"-21.318447"},{"dogid":"1","latitude":"14.00000","longitude":"-18.536711"}]
What I am doing (well I believe i am) is taking the values from the link and saving them to a string. Secondly, save that string value to an array. Then, I go thru this array and save out the latitude and longitude and assign it to CLLocationCordinate 2dcoord. After whch I expect both pins to be dropped on whatever location they received.
However, what occurs is: Upon running the program, when it arrives on this lin
for (NSDictionary *row in locations) {
the loop is not run to assign the values, and it jumps to the end. Oddly, a single pin is dropped on the map (thou location doesnt appear to be the values that it waas passed).
Would appreciate a little incite into the matter.
Thanks
- (void)viewDidAppear:(BOOL)animated
{
NSMutableArray *annotations = [[NSMutableArray alloc] init];
NSURL *myURL =[NSURL URLWithString:#"link.php"];
NSError *error=nil;
NSString *str=[NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
CLLocationCoordinate2D coord;
NSArray *locations=[NSArray arrayWithContentsOfFile:str];
for (NSDictionary *row in locations) {
NSNumber *latitude = [row objectForKey:#"latitude"];
NSNumber *longitude = [row objectForKey:#"longitude"];
// NSString *title = [row objectForKey:#"title"];
//Create coordinates from the latitude and longitude values
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
}
MKPointAnnotation *pin = [[MKPointAnnotation alloc] init];
pin.coordinate = coord;
[self.mapView addAnnotation:pin];
}
It looks like you are trying to save api response to and Array.
Api always returns json string which is NSString.
You need to convert decode json string.
In your case
NSString *str=[NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
you need to decode str with [NSJSONSerialization JSONObjectWithData:<#(NSData )#> options:<#(NSJSONReadingOptions)#> error:<#(NSError *)#>] which give you proper array of dictionary.
Hope it will help you

Google Maps - Make route line follow streets when map zoomed in

I'm getting the same issue as described in following SO questions:
(The route lines is not following the streets when I zoom in)
MapKit - Make route line follow streets when map zoomed in
and
Route drawing on Google Maps for iOS not following the street lines
But seems there are no any answer which solved mentioned issue.
I'm adding to points to the my GMSMapView map by following function:
-(void) addPointToMap:(CLLocationCoordinate2D) coordinate
{
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(
coordinate.latitude,
coordinate.longitude);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.map = mapView_;
[waypoints_ addObject:marker];
NSString *positionString = [[NSString alloc] initWithFormat:#"%f,%f",
coordinate.latitude,coordinate.longitude];
[waypointStrings_ addObject:positionString];
if([waypoints_ count]>1){
NSString *sensor = #"false";
NSArray *parameters = [NSArray arrayWithObjects:sensor, waypointStrings_,
nil];
NSArray *keys = [NSArray arrayWithObjects:#"sensor", #"waypoints", nil];
NSDictionary *query = [NSDictionary dictionaryWithObjects:parameters
forKeys:keys];
MDDirectionService *mds=[[MDDirectionService alloc] init];
SEL selector = #selector(addDirections:);
[mds setDirectionsQuery:query
withSelector:selector
withDelegate:self];
}
}
and here are setDirectionsQuery function:
static NSString *kMDDirectionsURL = #"http://maps.googleapis.com/maps/api/directions/json?";
- (void)setDirectionsQuery:(NSDictionary *)query withSelector:(SEL)selector
withDelegate:(id)delegate{
NSArray *waypoints = [query objectForKey:#"waypoints"];
NSString *origin = [waypoints objectAtIndex:0];
int waypointCount = [waypoints count];
int destinationPos = waypointCount -1;
NSString *destination = [waypoints objectAtIndex:destinationPos];
NSString *sensor = [query objectForKey:#"sensor"];
NSMutableString *url =
[NSMutableString stringWithFormat:#"%#&origin=%#&destination=%#&sensor=%#",
kMDDirectionsURL,origin,destination, sensor];
if(waypointCount>2) {
[url appendString:#"&waypoints=optimize:true"];
int wpCount = waypointCount-2;
for(int i=1;i<wpCount;i++){
[url appendString: #"|"];
[url appendString:[waypoints objectAtIndex:i]];
}
}
url = [url
stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
_directionsURL = [NSURL URLWithString:url];
[self retrieveDirections:selector withDelegate:delegate];
}
Note: I have followed this Google tutorial and modified it a little bit:
https://www.youtube.com/watch?v=AdV7bCWuDYg
Thanks in advance, any help will be appreciated!
Finally I have found solution, Thanks to the WWJD's last edit in his question!
Route drawing on Google Maps for iOS not following the street lines
From the answer:
What I basically did before was that I was getting and working only with the information I'm receiving in the routes while if you check the JSON file you're receiving from Google Directions API, you'll see that you receive much more information in the and the . This is the information we need to produce the proper results and the right polyline.

how to remove particular markers from GMS?

I asked earlier how to show different markerInfoWindow in this question,
and now I'm trying to delete a particular marker when the user clicks on the button on the left corner.
first in .h file :
NSMutableArray *ADSMarray;
GMSMarker *adsMarker;
Then I created Ads marker like this:
for (int l=0 ; l<self.ADS.count; l++) {
CLLocationCoordinate2D pos = CLLocationCoordinate2DMake([[[self.ADS objectAtIndex:l] objectForKey:#"lati"] doubleValue],[[[self.ADS objectAtIndex:l] objectForKey:#"longi"] doubleValue]);
NSLog(#"Ads:: %f",[[[self.ADS objectAtIndex:l] objectForKey:#"longi"] doubleValue]);
adsMarker = [[GMSMarker alloc]init];
adsMarker.position=pos;
//marker.infoWindowAnchor = CGPointMake(0.44f, 0.45f);
adsMarker.draggable = NO;
adsMarker.appearAnimation=YES;
NSMutableArray*tempArray = [[NSMutableArray
alloc] init];
[tempArray addObject:#"ADS"];
[tempArray addObject:[self.ADS objectAtIndex:l]];
adsMarker.userData = tempArray;
adsMarker.map = mapView_;
adsMarker.icon=[GMSMarker markerImageWithColor:[UIColor blueColor]];
}
then in IBAction to remove them I wrote:
for (int i =0; i<self.ADS.count; i++) {
// adsMarker.map = nil;
[adsMarker setMap:nil];
}
When you add a marker store a reference to it. Then when you want to remove it, set its map property to nil - that will remove it from the map.
if you want to remove all markers in MapView you can use clear method that already built in GSM ..
Example:
[self.mapView clear];
link:
Remove a marker
and if you want to remove all markers with specific color you can use this code if the user click on blue markers button :
NSArray *blueMarkers = #[ markerBlue1, markerBlue2 ];
NSArray *greenMarkers = #[ markerGreen1, markerGreen2 ];
NSArray *purpleMarkers = #[ markerPurple1, markerPurple2 ];
for (GMSMarker *marker in blueMarkers ){
marker.map = nil;
}
To remove all markers
mapView.clear()
To remove a specific marker
myMarker.map = nil

Plotting multiple markers in Google Maps

Hi I am working on Google Maps SDK for ios. I want to plot a number of markers in Google maps from NSArray which contains location name, latitude and longitude.
I tried using For loops which seems a little lame already but,
for(int i=0;i<=[myArray count];i++){
self.view = mapView_;
NSString *lat = [[myArray objectAtIndex:i] objectForKey:#"latitude"];
NSString *lon = [[myArray objectAtIndex:i] objectForKey:#"longitude"];
double lt=[lat doubleValue];
double ln=[lon doubleValue];
NSString *name = [[myArray objectAtIndex:i] objectForKey:#"name"];
NSLog(#"%# and %# and %f and %f of %#",lat,lon, lt,ln,name);
GMSMarker *marker = [[GMSMarker alloc] init];
marker.animated=YES;
marker.position = CLLocationCoordinate2DMake(lt,ln);
marker.title = name;
marker.snippet = #"Kathmandu";
marker.map = mapView_;
}
Here myarray is the array that has location name , latitude longitude in string format which I converted it to double. When I run this code Xcode shows me NSRangeException: index beyond bounds, which is probably because I am trying to use same object to display different indexes in same map. But at the same time, I couldnot think of any way to use GMSMarker as array.
I could however plot multiple markers if I used different GMSMarker objects, but that doesnot solve my problem. I made another object like this, using two GMSMarker objects work to show two markers on the same map.
GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1.animated=YES;
marker1.position = CLLocationCoordinate2DMake(lt,ln);
marker1.title = name;
marker1.snippet = #"Kathmandu";
marker1.map = mapView_;
Any help?
But at the same time, I couldnot think of any way to use GMSMarker as array.
try this:
NSMutableArray *markersArray = [[NSMutableArray alloc] init];
for(int i=0;i<[myArray count];i++){
// ... initialise marker here
marker.map = mapView_;
[markersArray addObject:marker];
[marker release];
}

Resources