Map Annotations from JSON -- No annotations showing up [duplicate] - ios

I've been through several different tutorials trying to get this working, but they seem to gloss over some crucial steps that a beginner might not know.
I have a JSON file at a URL with name, latitude, and longitude listed. How can I import that to an array or dictionary (I don't know the difference), and then iterate over it and create a new annotation with each iteration.
IOS6, Storyboards
_ Added Code _
ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController {}
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) NSMutableData *downloadData;
#end
ViewController.m
#import "ViewController.h"
#import "MapViewAnnotation.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_downloadData = [NSMutableData new];
NSURL *requestURL = [NSURL URLWithString:#"OMITTED/apptest/locations.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
id parsed = [NSJSONSerialization JSONObjectWithData:_downloadData options:kNilOptions error:nil];
for (NSDictionary *pointInfo in parsed)
{
NSLog([parsed objectForKey:#"name"]);
double xCoord = [(NSNumber*)[parsed objectForKey:#"lat"] doubleValue];
double yCoord = [(NSNumber*)[parsed objectForKey:#"lon"] doubleValue];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(xCoord, yCoord);
MKPointAnnotation *point = [MKPointAnnotation new];
point.coordinate = coords;
point.title = [parsed objectForKey:#"name"];
[self.mapView addAnnotation:point]; // or whatever your map view's variable name is
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidUnload {
[super viewDidUnload];
// ARC Problem --- [_mapView release];
self.mapView = nil;
}
#end

With iOS 5 there's a JSONSerializer class that can convert the raw JSON data from your URL into an array or dictionary as appropriate.
You'll need to download the data from the server:
NSURL *requestURL = [NSURL URLWithString:#"<your url here>"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
Then you'll add these delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
id parsed = [NSJSONSerialization JSONObjectWithData:_downloadData options:kNilOptions error:nil];
}
_downloadData is an instance variable or property of your class of type NSMutableData.
That parsed variable will contain your data from the server. It's probably an array if it's a list of points, so you can iterate through it using fast enumeration:
for (NSDictionary *pointInfo in parsed) {
double xCoord = [(NSNumber*)[parsed objectForKey:#"<key for lat coord>"] doubleValue];
double yCoord = [(NSNumber*)[parsed objectForKey:#"<key for long coord>"] doubleValue];
CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(xCoord, yCoord);
MKPointAnnotation *point = [[MKPointAnnotation new] autorelease];
point.coordinate = coords;
point.title = [parsed objectForKey:#"<key for title>"];
[self.mapView addAnnotation:point]; // or whatever your map view's variable name is
}

I have an open source project on GitHub that uses the serializer with the NSCoding protocol so you can automatically create instances right from the JSON stream.
It's here.

Related

How to feed existing markers into a marker cluster in GoogleMap iOS SDK?

I am developing an app using Google Map iOS SDK (Objective C).
Done so far:
Loaded markers from the server in map view
Generate random clusters only.
When I run the project it looks like this.
Screen shot of map view
It shows both markers and clusters both in the map view at zoom level 10. But I wanted to show clusters first then when I zoomed in it should show the real markers. Not the randomly generated markers that I created because I don't know a way to show the clusters in the map.
Here is the full code with fake URL link:
#import "ViewController.h"
//#import "CSMarker.h"
#import <GoogleMaps/GoogleMaps.h>
#import <Google-Maps-iOS-Utils/GMUMarkerClustering.h>
//importing POI Item object - points of interest
#interface POIItem : NSObject<GMUClusterItem>
#property(nonatomic, readonly) CLLocationCoordinate2D position;
#property(nonatomic, readonly) NSString *name;
- (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name;
#end
#implementation POIItem
- (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name {
if ((self = [super init])) {
_position = position;
_name = [name copy];
}
return self;
}
#end
//implementation start - map view controller
static const NSUInteger kClusterItemCount = 60;
static const double kCameraLatitude = 25.277683999999997;
static const double kCameraLongitude = 55.309802999999995;
#interface ViewController ()<GMUClusterManagerDelegate, GMSMapViewDelegate>
{
NSMutableArray *waypoints_;
NSMutableArray *waypointStrings_;
GMSMapView *_mapView;
GMUClusterManager *_clusterManager;
}
#property(strong, nonatomic) NSURLSession *markerSession;
#property(strong, nonatomic) GMSMapView *mapView;
#property(copy, nonatomic) NSSet *markers;
#property(nonatomic, strong) NSMutableArray *markersArray;
#end
#implementation ViewController
#synthesize gs;
- (void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:kCameraLatitude
longitude:kCameraLongitude
zoom:10];
self.mapView =
[GMSMapView mapWithFrame:self.view.bounds camera:camera];
[self.view addSubview:self.mapView];
self.mapView.settings.compassButton = YES;
self.mapView.settings.myLocationButton = YES;
//setup the cluster manager
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
config.URLCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
diskCapacity:10 * 1024 * 1024
diskPath:#"MarkerData"];
self.markerSession = [NSURLSession sessionWithConfiguration:config];
[self downloadMarkerData];
//cluster load setup
id<GMUClusterAlgorithm> algorithm = [[GMUNonHierarchicalDistanceBasedAlgorithm alloc] init];
id<GMUClusterIconGenerator> iconGenerator = [[GMUDefaultClusterIconGenerator alloc] init];
id<GMUClusterRenderer> renderer =
[[GMUDefaultClusterRenderer alloc] initWithMapView:self.mapView
clusterIconGenerator:iconGenerator];
_clusterManager =
[[GMUClusterManager alloc] initWithMap:self.mapView algorithm:algorithm renderer:renderer];
// Generate and add random items to the cluster manager.
[self generateClusterItems];
// Call cluster() after items have been added to perform the clustering and rendering on map.
[_clusterManager cluster];
// Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
[_clusterManager setDelegate:self mapDelegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSMutableArray *)markersArray
{
if (!_markersArray) {
_markersArray = [NSMutableArray array];
}
return _markersArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//downloading marker data
- (void)downloadMarkerData {
NSURL *lakesURL =
[NSURL URLWithString:#"http://myscrap.com/xxx.php/webservice/xxx/xxxx"];
NSURLSessionDataTask *task = [self.markerSession dataTaskWithURL:lakesURL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *e)
{
NSArray *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"json: %#",json);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self createMarkerObjectsWithJson:json];
}];
}];
[task resume];
}
-(void)drawMarkers
{
for(GMSMarker *marker in self.markers) {
if(marker.map == nil) {
marker.map = self.mapView;
}
}
}
-(void)createMarkerObjectsWithJson:(NSArray *)json
{
NSMutableSet *mutableSet = [[NSMutableSet alloc] initWithSet:self.markers];
for (NSDictionary *markerData in json) {
GMSMarker *newMarker = [[GMSMarker alloc] init];
// newMarker.appearAnimation = [markerData[#"id"] integerValue];
newMarker.position = CLLocationCoordinate2DMake([markerData[#"latitud"] doubleValue],
[markerData[#"longitude"] doubleValue]);
newMarker.title = markerData[#"name"];
newMarker.snippet = markerData[#"adress"];
// [mutableSet addObject:newMarker];
newMarker.map=self.mapView;
}
self.markers =[mutableSet copy];
[self drawMarkers];
}
#pragma mark GMUClusterManagerDelegate
- (void)clusterManager:(GMUClusterManager *)clusterManager didTapCluster:(id<GMUCluster>)cluster {
GMSCameraPosition *newCamera =
[GMSCameraPosition cameraWithTarget:cluster.position zoom:_mapView.camera.zoom + 1];
GMSCameraUpdate *update = [GMSCameraUpdate setCamera:newCamera];
[_mapView moveCamera:update];
}
#pragma mark GMSMapViewDelegate
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
POIItem *poiItem = marker.userData;
if (poiItem != nil) {
NSLog(#"Did tap marker for cluster item %#", poiItem.name);
} else {
NSLog(#"Did tap a normal marker");
}
return NO;
}
#pragma mark Private
// Randomly generates cluster items within some extent of the camera and adds them to the
// cluster manager.
- (void)generateClusterItems {
const double extent = 0.2;
for (int index = 1; index <= kClusterItemCount; ++index) {
double lat = kCameraLatitude + extent * [self randomScale];
double lng = kCameraLongitude + extent * [self randomScale];
NSString *name = [NSString stringWithFormat:#"Item %d", index];
id<GMUClusterItem> item =
[[POIItem alloc] initWithPosition:CLLocationCoordinate2DMake(lat, lng) name:name];
[_clusterManager addItem:item];
}
}
// Returns a random value between -1.0 and 1.0.
- (double)randomScale {
return (double)arc4random() / UINT32_MAX * 2.0 - 1.0;
}
try changing in view did load
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:kCameraLatitude longitude:kCameraLongitude zoom:4];
the zoom to a 5 or 4. It then should show the clusters and not the markers. When you zoom in, it will show the "real" markers.

How to add events by JSON in MBCalendarKit

I used a storyboard and ios 9 , Xcode 7.2, in this project used a calendar view and event show by web server fetch data.
I added calendar kit framework and also two file add my project first is CKDemoViewController.h and second is CKDemoViewController.m, This time create a static events. but i want to create a dynamic events. so how it possible. I tried to many times but could not create dynamic events. How it possible, please help, Thank You.
CKDemoViewController.m
#import "CKDemoViewController.h"
#import "NSCalendarCategories.h"
#import "NSDate+Components.h"
#interface CKDemoViewController () <CKCalendarViewDelegate, CKCalendarViewDataSource>
{
NSArray*date;
NSArray*title;
NSArray*img;
NSArray*des;
NSArray*evnt_ary;
NSArray*timeary;
}
#property (nonatomic, strong) NSMutableDictionary *data;
#end
#implementation CKDemoViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_event.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
self.data = [[NSMutableDictionary alloc] init];
[self setDataSource:self];
[self setDelegate:self];
// An event for the new MBCalendarKit release.
NSString *title = NSLocalizedString(#"Release MBCalendarKit 2.2.4", #"");
NSDate *date = [NSDate dateWithDay: 12 month:11 year:2016];
CKCalendarEvent *releaseUpdatedCalendarKit = [CKCalendarEvent eventWithTitle:title andDate:date andInfo:nil];
// An event for the new Hunger Games movie.
NSString *title2 = NSLocalizedString(#"The Hunger Games: Mockingjay, Part 1", #"");
NSDate *date2 = [NSDate dateWithDay:21 month:11 year:2014];
CKCalendarEvent *mockingJay = [CKCalendarEvent eventWithTitle:title2 andDate:date2 andInfo:nil];
// Integrate MBCalendarKit
NSString *integrationTitle = NSLocalizedString(#"Integrate MBCalendarKit", #"");
NSDate *integrationDate = date2;
CKCalendarEvent *integrationEvent = [CKCalendarEvent eventWithTitle:integrationTitle andDate:integrationDate andInfo:nil];
// An event for the new MBCalendarKit release.
NSString *title3 = NSLocalizedString(#"Fix bug where events don't show up immediately.", #"");
NSDate *date3 = [NSDate dateWithDay:29 month:11 year:2014];
CKCalendarEvent *fixBug = [CKCalendarEvent eventWithTitle:title3 andDate:date3 andInfo:nil];
self.data[date] = #[releaseUpdatedCalendarKit];
self.data[date2] = #[mockingJay, integrationEvent];
self.data[date3] = #[fixBug];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",json);
NSArray *results = [json objectForKey:#"status"];
title = [[results valueForKey:#"event"]valueForKey:#"event_title"];
NSLog(#"event name fetch %#",title);
date =[[results valueForKey:#"event"]valueForKey:#"event_date"];
NSLog(#"event fetch %#",date);
img =[[results valueForKey:#"event"]valueForKey:#"img"];
des =[[results valueForKey:#"event"]valueForKey:#"event_detail"];
evnt_ary =[[results valueForKey:#"event"]valueForKey:#"event_name"];
timeary =[[results valueForKey:#"event"]valueForKey:#"event_time"];
}
#pragma mark - CKCalendarViewDataSource
- (NSArray *)calendarView:(CKCalendarView *)calendarView eventsForDate:(NSDate *)date
{
return [self data][date];
}
#pragma mark - CKCalendarViewDelegate
// Called before/after the selected date changes
- (void)calendarView:(CKCalendarView *)CalendarView willSelectDate:(NSDate *)date
{
}
- (void)calendarView:(CKCalendarView *)CalendarView didSelectDate:(NSDate *)date
{
}
// A row is selected in the events table. (Use to push a detail view or whatever.)
- (void)calendarView:(CKCalendarView *)CalendarView didSelectEvent:(CKCalendarEvent *)event
{
}
#end
Refer this link for code only one event set another your logic:
https://www.dropbox.com/home?preview=proj.zip
I am also solve this question in MBCalendar kit framework how to add in my project

Unable to draw direction route by using MapBox using Xcode 6.4

I am Using MapBox to draw direction route for source and destination point.
When I use the sample URL provided by the Website then I am able to draw route line.
But when I use my own co-ordinates then I am not able to draw any route.
I am not getting error message or any logs.
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *_responseData;
NSDictionary *_directionApiResponseDict;
NSArray *_coordinatesArray;
BOOL isControllerPoped;
}
#property (nonatomic) MGLMapView *mapView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// initialize the map view
// NSURL *styleURL = [NSURL URLWithString:#"asset://styles/dark-v8.json"];
self.mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds];
self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.mapView.delegate = self;
//set the map's center coordinate
[self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(28.57,77.32)
zoomLevel:15
animated:NO];
[self.view addSubview:self.mapView];
// MGLPointAnnotation *point = [[MGLPointAnnotation alloc] init];
// point.coordinate = CLLocationCoordinate2DMake(-122.42,37.78);
// point.title = #"Hello world!";
// point.subtitle = #"Welcome to The Ellipse.";
//
// // Add annotation `point` to the map
// [self.mapView addAnnotation:point];
NSString *urlString = [NSString stringWithFormat:#"https://api.mapbox.com/v4/directions/mapbox.driving/28.57,77.32;28.11,77.22.json?access_token=pk.eyJ1IjoicmFodWx2cyIsImEiOiJjaWdjN2w1c3YycWNxdmptM3YzNzR4dWR5In0.jU9egzoUg46b4fLUQlL-Bg"];
//https://api.mapbox.com/v4/directions/mapbox.driving/-122.42,37.78;-77.03,38.91.json?alternatives=false&instructions=html&geometry=polyline&steps=false&&access_token=<your%20access%20token> these co-ordinates works fine
NSLog(#"URRRL=%#",urlString);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation {
return YES;
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
_directionApiResponseDict = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
NSArray *rootsDictArray = [_directionApiResponseDict valueForKey:#"routes"];
if(rootsDictArray && rootsDictArray.count > 0)
{
NSDictionary *rootDict = [rootsDictArray objectAtIndex:0];
if(rootDict && [rootDict valueForKey:#"geometry"])
{
NSDictionary *geoDict = [rootDict valueForKey:#"geometry"];
if(geoDict && [geoDict isKindOfClass:[NSDictionary class]])
{
_coordinatesArray = [geoDict valueForKey:#"coordinates"];
if(_coordinatesArray)
{
[self drawPolyline];
}
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)drawPolyline
{
// Perform GeoJSON parsing on a background thread
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(backgroundQueue, ^(void)
{
// Get the raw array of coordinates for our line
NSArray *rawCoordinates = _coordinatesArray;
NSUInteger coordinatesCount = rawCoordinates.count;
// Create a coordinates array, sized to fit all of the coordinates in the line.
// This array will hold the properly formatted coordinates for our MGLPolyline.
CLLocationCoordinate2D coordinates[coordinatesCount];
int validCoordinates=0;
// Iterate over `rawCoordinates` once for each coordinate on the line
for (NSUInteger index = 0; index < coordinatesCount; index++)
{
// Get the individual coordinate for this index
NSArray *point = [rawCoordinates objectAtIndex:index];
// GeoJSON is "longitude, latitude" order, but we need the opposite
if([point count]>1){
CLLocationDegrees lat = [[point objectAtIndex:1] doubleValue];
CLLocationDegrees lng = [[point objectAtIndex:0] doubleValue];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
// Add this formatted coordinate to the final coordinates array at the same index
coordinates[validCoordinates] = coordinate;
validCoordinates++;
}
}
// Create our polyline with the formatted coordinates array
MGLPolyline *polyline = [MGLPolyline polylineWithCoordinates:coordinates count:validCoordinates];
// Optionally set the title of the polyline, which can be used for:
// - Callout view
// - Object identification
// In this case, set it to the name included in the GeoJSON
// Add the polyline to the map, back on the main thread
// Use weak reference to self to prevent retain cycle
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[weakSelf.mapView addAnnotation:polyline];
});
});
}
- (CGFloat)mapView:(MGLMapView *)mapView alphaForShapeAnnotation:(MGLShape *)annotation
{
// Set the alpha for all shape annotations to 1 (full opacity)
return 1.0f;
}
- (CGFloat)mapView:(MGLMapView *)mapView lineWidthForPolylineAnnotation:(MGLPolyline *)annotation
{
// Set the line width for polyline annotations
return 2.0f;
}
- (UIColor *)mapView:(MGLMapView *)mapView strokeColorForShapeAnnotation:(MGLShape *)annotation
{
// Set the stroke color for shape annotations
// ... but give our polyline a unique color by checking for its `title` property
if ([annotation.title isEqualToString:#"Crema to Council Crest"])
{
// Mapbox cyan
return [UIColor colorWithRed:59.0f/255.0f green:178.0f/255.0f blue:208.0f/255.0f alpha:1.0f];
}
else
{
return [UIColor redColor];
}
}
#pragma mark - Map Delegate methods
- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {
return nil;
//
// MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:kImageIdentifire];
//
// if ( ! annotationImage)
// {
// // Leaning Tower of Pisa by Stefan Spieler from the Noun Project
// UIImage *image = [UIImage imageNamed:#"annotation.png"];
// annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:kImageIdentifire];
// }
//
// return annotationImage;
}
#end
There is an issue with your Mapbox URL call.
From Mapbox API Documentation:
a semicolon-separated list of {longitude},{latitude} coordinate pairs
to visit in order, containing at least two elements (origin and
destination). There can be anywhere between 2 and 25 coordinate pairs
in the list.
But you used the longitude value as latitude and the latitude value as longitude. Based on your CLLocationCoordinate2DMake method call that has these parameters:
CLLocationCoordinate2DMake(CLLocationDegrees latitude,
CLLocationDegrees longitude)
As you can see, in the Mapbox call URL you should put first the longitude and then the latitude.
Inverse the latitude and longitude in your url and everything will be OK. I tested with your link in the browser and I got directions.
You might be interested in the Mapbox Swift toolkit for directions:
https://github.com/mapbox/MapboxDirections.swift
It's meant to work like Apple's MKDirections. You can use it in Objective-C code by importing the automatically-generated <TargetName>-Swift.h into your code once the Swift code is also in the target.

setting variable returned from rest request in objective c ios

I'm making a rest call and returning lat longs with the call. For now I just return the coords passed because im just trying to learn the workings of objective C and iphone programing its been a few years. I have some code currently where I define some public vars that I set with in my rest function but when I go to draw them on a map they are 0 but if i break inside the function where im setting the label.text elements to the values they are set to the correct value but when it finishes the rest call they are reset. Not sure why
//
// ViewController.m
// REST
//
// Created by Grant Zukel on 8/5/15.
// Copyright © 2015 Grant Zukel. All rights reserved.
//
#import "ViewController.h"
#import GoogleMaps;
#interface ViewController ()
{
}
#end
#implementation ViewController{
GMSMapView *mapView_;
#public NSInteger int_lat;
#public NSInteger int_lon;
}
- (IBAction)drawMap;
{
NSURL *url = [NSURL URLWithString:#"http://127.0.0.1:8001/test/39.748922&-104.986147"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
//NSLog([greeting objectForKey:#"status"]);
self.greetingContent.text = [greeting objectForKey:#"content"];
self.greetingId.text = [greeting objectForKey:#"id"];
NSString *latitude = ([[greeting objectForKey:#"coords"] objectForKey:#"latitude"]);
NSString *longitude = ([[greeting objectForKey:#"coords"] objectForKey:#"longitude"]);
self.testLat.text = latitude;
self.testLon.text = longitude;
int_lat = [latitude intValue];
int_lon = [longitude intValue];
}
}];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:int_lat
longitude:int_lon
zoom:1];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
self.view = mapView_;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(int_lat, int_lon);
marker.title = #"Test";
marker.snippet = #"Test";
marker.map = mapView_;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self drawMap];
//NSString *temperatureString = [self getStringForTemperature:A base:B];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

Passing Co-ordinates from one view to another

Now i am updating the code with the perfect output. This may help my friends to place the correct markers.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import
#import "fetchurl.h"
#import
#interface placevcViewController : UIViewController
{
CLLocationDegrees lat;
CLLocationDegrees lng;
CLLocationCoordinate2D local;
}
-(id)init;
-(void)location:(CLLocationManager *)address;
#property (nonatomic, strong) NSDictionary *location;
#property (strong, nonatomic) UITextField *addressfeild;
#property (strong, nonatomic) fetchurl *fu;
#property (strong, nonatomic) GMSMapView *map;
#property (strong, nonatomic) CLLocationManager *locationManager;
#property (strong, nonatomic) GMSCameraPosition *camera;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
placevcViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "placevcViewController.h"
#interface placevcViewController ()
#end
#implementation placevcViewController
#synthesize addressfeild, map,fu,locationManager,camera;
-(id)init
{
self = [super init];
location = [[NSDictionary alloc] initWithObjectsAndKeys:#"0.0",#"lat",#"0.0",#"lng",#"Null Island",#"adress",#"NULL Home",#"name", nil];
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
lat = locationManager.location.coordinate.latitude;
lng = locationManager.location.coordinate.longitude;
local = CLLocationCoordinate2DMake(lat, lng);
fu = [[fetchurl alloc]init];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude: lng zoom:12];
map = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:camera];
[self.view addSubview:map];
map.settings.myLocationButton = YES;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(200, 65, 100, 40);
[button setTitle:#"SEARCH" forState:UIControlStateNormal];
[button addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
addressfeild = [[UITextField alloc] initWithFrame:CGRectMake(10, 68, 200, 30)];
addressfeild.placeholder = #"SEARCH";
[addressfeild setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:addressfeild];
}
-(IBAction)search:(id)sender
{
[self location:str1];
}
-(void)location:(NSString *)address
{
NSString *baseUrl =#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
NSString *url = [NSString stringWithFormat:#"%#location=%#&radius=10000&name=dominos&sensor=false&key=AIzaSyCczXEpxw19qAXQMEUUA98OsMaOESNSOjM",baseUrl,address];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *queryUrl = [NSURL URLWithString:url];
NSLog(#"query url%#",queryUrl);
dispatch_async(dispatch_get_main_queue(), ^{
NSData *data = [NSData dataWithContentsOfURL:queryUrl];
[self fetchData:data];
});
}
-(void)fetchData:(NSData *)data
{
NSString *data1 = [NSString stringWithUTF8String:[data bytes]];
// NSLog(#"Response data: %#", data1);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* results =[json objectForKey:#"results"];
//NSLog(#"Data is:%#" ,results);
for (int i = 0;i <[results count]; i++) {
NSDictionary *result = [results objectAtIndex:i];
// NSLog(#"Data is %#", result);
NSString *address = [result objectForKey:#"vicinity"];
// NSLog(#"Address is %#", address);
NSString *name = [result objectForKey:#"name"];
//NSLog(#"name is %#", name);
NSDictionary *geometry = [result objectForKey: #"geometry"];
NSDictionary *locations = [geometry objectForKey:#"location"];
NSString *lat =[locations objectForKey:#"lat"];
NSString *lng =[locations objectForKey:#"lng"];
//NSLog(#"longitude is %#", lng);
NSDictionary *gc = [[NSDictionary alloc]initWithObjectsAndKeys:lat,#"lat",lng,#"lng",address,#"address",name,#"name", nil];
location = gc;
double lat1 = [[location objectForKey:#"lat"] doubleValue];
NSLog(#"Marker position%f",lat1);
double lng1 = [[location objectForKey:#"lng"] doubleValue];
NSLog(#"Marker position%f",lng1);
GMSMarker *marker = [[GMSMarker alloc]init];
CLLocationCoordinate2D local = CLLocationCoordinate2DMake(lat1, lng1);
marker.position = local;
marker.title = [ location objectForKey:#"name"];
NSLog(#"Address is %#",marker.title);
marker.snippet = [location objectForKey:#"address"];
marker.map = map;
GMSCameraUpdate *cams = [GMSCameraUpdate setTarget:local zoom:12];
[map animateWithCameraUpdate:cams];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I am facing trouble with the functions which i bolded up. Actually i want to pass the co-ordinates of my current location from placevcViewController.m to fetchurl.m through a function -(void)location:(CLLocationManager *)address withCallback:(SEL)sel withDelegate: (id)delegate; , but somehow it is not working. Either the function is incorrect or i am not using the correct data type for fetching the co-ordinates.
Updates :
I have update the above code in fetchurl.m file(you can c ** there the code within the stars is upadted ) , and the updation is helping me to get the array of multiple locations. But now i am not getting how to add the marker on each location.
To use the delegate-protocol pattern successfully, you need some additional setup:
PlacevcViewController.h needs to define both a delegate property, and define the protocol:
#property (nonatomic, assign) id delegate;
//at the bottom of your file, below the #interface ... #end
#protocol nameOfYourProtocol <NSObject>
-(void)methodForDoingSomething:(SomeClass*)argument;
#end
Then within PlacevcViewController.m you can call your delegate method like this:
[self.delegate methodForDoingSomething:anArgument];
Then you assign your delegate and implement the method in the target class (fetchUrl.h in your case)
//declare conformity to the protocol like this in the header file
#interface fetchurl : NSObject <nameOfYourProtocol>
and finally in the fetchUrl.m file:
//assign the delegate to self when creating an instance of fetchUrl
fu = [[fetchUrl alloc] init];
[fu setDelegate:self];
//implement the delegate method
- (void)methodForDoingSomething:(SomeClass*)argument {
//your code goes here
}
While there is nothing right or wrong about using the delegate-protocol pattern, from what I can tell of your example a simpler approach might be to just define a method within fetchUrl that returns the items you need and let the owner of that instance of fetchUrl handle it. ie:
- (NSDictionary*)fetchData:(NSData*)data {
//do the work and create a dictionary
//return theDictionary
}
and then just consume the result in your placevcViewController:
NSDictionary* results = [fu fetchData:someData];
//now work with the results

Resources