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
Related
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.
I want to find road distance between two coordinates. Firstly i am taking source and destination from user and then using googleMap api i find the coordinates.
I am able to find coordinates and air distance but i am unable to find road distance and draw a polyline between them. Every method available on google is for older xcode and not supported on xcode 6.
Method i am using for finding coordinates
-(CLLocationCoordinate2D)FindCoordinates:(NSString *)place
{
NSString *addresss = place;
NSString *esc_addr = [addresss stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: #"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
NSDictionary *googleResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *resultsDict = [googleResponse valueForKey: #"results"]; // get the results dictionary
NSDictionary *geometryDict = [ resultsDict valueForKey: #"geometry"]; // geometry dictionary within the results dictionary
NSDictionary *locationDict = [ geometryDict valueForKey: #"location"]; // location dictionary within the geometry dictionary
// nslo (#”– returning latitude & longitude from google –”);
NSArray *latArray = [locationDict valueForKey: #"lat"]; NSString *latString = [latArray lastObject]; // (one element) array entries provided by the json parser
NSArray *lngArray = [locationDict valueForKey: #"lng"]; NSString *lngString = [lngArray lastObject]; // (one element) array entries provided by the json parser
myLocation.latitude = [latString doubleValue]; // the json parser uses NSArrays which don’t support “doubleValue”
myLocation.longitude = [lngString doubleValue];
return myLocation;
}
method i am using for finding distance
-(IBAction)getLocation:(id)sender
{
sourceLocation = [self FindCoordinates:source1.text];
NSLog(#"%#",[NSString stringWithFormat:#"Source lat:%f Source lon:%f",sourceLocation.latitude,sourceLocation.longitude]);
destinationLocation = [self getMe:destination1.text];
NSLog(#"%#",[NSString stringWithFormat:#"Desti lat:%f Desti lon:%f",destinationLocation.latitude,destinationLocation.longitude]);
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:sourceLocation.latitude longitude:sourceLocation.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:destinationLocation.latitude longitude:destinationLocation.longitude];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSLog(#"%#",[NSString stringWithFormat:#"Distance iin KMeteres %f",distance/1000]); // Gives me air distance
MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ]; // Not able to modify these cordinates
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:#""];
MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:#"",#"", nil] ];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:#""];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeWalking];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
NSLog(#"response = %#",response);
NSArray *arrRoutes = [response routes];
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[map addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
NSLog(#"Total Steps : %lu",(unsigned long)[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Rout Instruction : %#",[obj instructions]);
NSLog(#"Rout Distance : %f",[obj distance]);
}];
}];
}];
}
How can draw a polyline also.
You have to use MKPolylineRenderer for iOS 8
Following is the code for adding MKPolyline by tapping on locations may you get help.
Pin.h
#import <Foundation/Foundation.h>
#import MapKit;
#interface Pin : NSObject <MKAnnotation>
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate;
#end
Pin.m
#import "Pin.h"
#implementation Pin
- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate {
self = [super init];
if (self) {
_coordinate = newCoordinate;
_title = #"Hello";
_subtitle = #"Are you still there?";
}
return self;
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#import MapKit;
#interface ViewController : UIViewController <MKMapViewDelegate>
#end
ViewController.m
#import "ViewController.h"
#import "Pin.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property (nonatomic, strong) NSMutableArray *allPins;
#property (nonatomic, strong) MKPolylineRenderer *lineView;
#property (nonatomic, strong) MKPolyline *polyline;
- (IBAction)drawLines:(id)sender;
- (IBAction)undoLastPin:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.allPins = [[NSMutableArray alloc]init];
// add a long press gesture
UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(addPin:)];
recognizer.minimumPressDuration = 0.5;
[self.mapView addGestureRecognizer:recognizer];
}
// let the user add their own pins
- (void)addPin:(UIGestureRecognizer *)recognizer {
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
// convert touched position to map coordinate
CGPoint userTouch = [recognizer locationInView:self.mapView];
CLLocationCoordinate2D mapPoint = [self.mapView convertPoint:userTouch toCoordinateFromView:self.mapView];
// and add it to our view and our array
Pin *newPin = [[Pin alloc]initWithCoordinate:mapPoint];
[self.mapView addAnnotation:newPin];
[self.allPins addObject:newPin];
[self drawLines:self];
}
- (IBAction)drawLines:(id)sender {
// HACK: for some reason this only updates the map view every other time
// and because life is too frigging short, let's just call it TWICE
[self drawLineSubroutine];
[self drawLineSubroutine];
}
- (IBAction)undoLastPin:(id)sender {
// grab the last Pin and remove it from our map view
Pin *latestPin = [self.allPins lastObject];
[self.mapView removeAnnotation:latestPin];
[self.allPins removeLastObject];
// redraw the polyline
[self drawLines:self];
}
- (void)drawLineSubroutine {
// remove polyline if one exists
[self.mapView removeOverlay:self.polyline];
// create an array of coordinates from allPins
CLLocationCoordinate2D coordinates[self.allPins.count];
int i = 0;
for (Pin *currentPin in self.allPins) {
coordinates[i] = currentPin.coordinate;
i++;
}
// create a polyline with all cooridnates
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:self.allPins.count];
[self.mapView addOverlay:polyline];
self.polyline = polyline;
// create an MKPolylineView and add it to the map view
self.lineView = [[MKPolylineRenderer alloc]initWithPolyline:self.polyline];
self.lineView.strokeColor = [UIColor redColor];
self.lineView.lineWidth = 5;
// for a laugh: how many polylines are we drawing here?
self.title = [[NSString alloc]initWithFormat:#"%lu", (unsigned long)self.mapView.overlays.count];
}
- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
return self.lineView;
}
#end
Get distance by
CLLocationDistance dist = [from distanceFromLocation:current];
I have implemented the module to pass the values from child viewController (SliderViewController ) to master viewController (MapViewController) but when it comes to the implementation, the position just added is lost and hence the array of coordinates cannot be added and hence presented? Besides saving the coordinates into the text file and reload, are there any other alternatives to save the array of coordinates ?
The below is my working:
ChildViewCOntroller
SliderViewController.h
#import <UIKit/UIKit.h>
#import "EFCircularSlider.h"
#protocol SliderViewControllerDelegate <NSObject>
- (void)passData:(float )itemVertical : (float )itemCircular ;
#end
#interface SliderViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *uiValue;
#property (strong, nonatomic) IBOutlet UISlider *uiSlider;
#property (strong, nonatomic) IBOutlet UIButton *btnReset;
#property (strong, nonatomic) IBOutlet UILabel *uiValue2;
#property (strong, nonatomic) EFCircularSlider* circularSlider;
#property (nonatomic) float verticalSliderValue;
#property (nonatomic) float circleSliderValue;
#property (nonatomic) id <SliderViewControllerDelegate> delegate;
- (IBAction)reset:(id)sender;
- (IBAction)sliderChange:(id)sender;
- (void)buttonClicked: (id)sender;
#end
SliderViewController.m
#import "SliderViewController.h"
#import <AudioToolbox/AudioServices.h>
#import "MapViewController.h"
#interface SliderViewController (){
NSString *valueV;
NSString *valueC;
}
#end
#implementation SliderViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_uiSlider.minimumValue = 0.0;
_uiSlider.maximumValue = 100.0;
[_uiSlider removeConstraints:_uiSlider.constraints];
[_uiSlider setTranslatesAutoresizingMaskIntoConstraints:YES];
float value = M_PI * -0.5 ;
_uiSlider.transform = CGAffineTransformMakeRotation(value);
CGRect sliderFrame = CGRectMake(60, 300, 100, 100);
_circularSlider = [[EFCircularSlider alloc] initWithFrame:sliderFrame];
[_circularSlider addTarget:self action:#selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:_circularSlider];
[_circularSlider setCurrentValue:10.0f];
[_uiSlider setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.5]];
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
CGFloat height = CGRectGetHeight(screen);
float scale = [[UIScreen mainScreen] scale];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake( 0, 450 ,width/2, 20);
[button setTitle:#"OK" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize:16.0];
button.titleLabel.adjustsFontSizeToFitWidth = TRUE;
[button setBackgroundColor:[UIColor orangeColor]];
[button addTarget: self
action: #selector(buttonClicked:)
forControlEvents: UIControlEventTouchDown];
[self.view addSubview:button];
}
- (void) buttonClicked: (id)sender
{
NSLog( #"Button clicked." );
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)valueChanged:(EFCircularSlider*)slider {
self.uiValue2.text = [NSString stringWithFormat:#"%.02f", slider.currentValue ];
_circleSliderValue = slider.currentValue;
valueC = self.uiValue2.text;
if(slider.currentValue > 20.0 && slider.currentValue < 30.0 ){
AudioServicesPlaySystemSound(1003);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
- (IBAction)reset:(id)sender {
[self writeToTextFile:valueV :valueC];
MapViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"MapViewController"];
sliderVC.verticalSliderValue = _uiSlider.value;
sliderVC.circleSliderValue =_circularSlider.currentValue;
[sliderVC passData:_uiSlider.value :_circularSlider.currentValue ];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void) writeToTextFile:(NSString*) values : (NSString*) values2 {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/slider.txt",documentsDirectory];
NSString *content = [NSString stringWithFormat:#"%#%#%#%#", values , #"\n" , values2 , #"\n" ];
[content writeToFile:fileName
atomically:YES
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSLog(#"%#",documentsDirectory);
[self displayContent];
}
-(void) displayContent{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/slider.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
NSLog(#"%#",content);
}
- (IBAction)sliderChange:(id)sender {
UISlider *slider = (UISlider *)sender;
NSString *newValue = [NSString stringWithFormat:#"%.2f" , slider.value];
_verticalSliderValue = slider.value;
self.uiValue.text = newValue;
valueV = self.uiValue.text;
if(slider.value > 30 && slider.value < 50){
AudioServicesPlaySystemSound(1003);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
MasterViewController
MapViewController.h
#import <MessageUI/MessageUI.h>
#import <GoogleMaps/GoogleMaps.h>
#import <UIKit/UIKit.h>
#import "SliderViewController.h"
#interface MapViewController : UIViewController<GMSMapViewDelegate , SliderViewControllerDelegate>{
}
#property (nonatomic) float verticalSliderValue;
#property (nonatomic) float circleSliderValue;
#end
MapViewCntroller.m
#import "MapViewController.h"
#import "CheckPoints.h"
#import "NSURLRequestSSL.h"
#import "ToastView.h"
#interface MapViewController () {
GMSMapView *mapView_;
NSMutableArray *array;
GMSCameraPosition *camera;
NSArray *_styles;
NSArray *_lengths;
NSArray *_polys;
double _pos, _step;
CLLocationCoordinate2D p;
}
#end
#implementation MapViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self getTime];
array = [[NSMutableArray alloc] init];
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.uisplatch
camera = [GMSCameraPosition cameraWithLatitude:22.2855200
longitude:114.1576900
zoom:12];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.delegate = self;
mapView_.myLocationEnabled = YES;
mapView_.settings.compassButton = YES;
mapView_.settings.myLocationButton = YES;
// mapView_.delegate = self;
self.view = mapView_;
// Creates a marker in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(22.2855200, 114.1576900);
marker.title = #"My place";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// defaults
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
if(latitide!=0.00&&longitude!=0.00) {
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(latitide, longitude);
marker.position = CLLocationCoordinate2DMake(position.latitude, position.longitude);
}
if(desp.length > 0 ){
marker.title = desp;
}
marker.snippet = #"HK";
marker.map = mapView_;
}
...
- (void)passData:(float )value1 : (float )valueCiruclar
{
NSLog(#"This was returned from ViewControllerB %ff",value1);
NSLog(#"This was returned from ViewControllerSlider %ff",valueCiruclar);
[mapView_ clear];
NSLog(#"This was map received");
CheckPoints *myCar=[[CheckPoints alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
float latitide = [defaults floatForKey:#"lati"];
float longitude = [defaults floatForKey:#"longi"];
NSString *desp = [defaults objectForKey:#"desp"];
[myCar setLatitude:latitide];
[myCar setLongitude:longitude];
[myCar setDesp:desp];
[myCar setState:[desp length] > 0 ? 0 : 1];
[CarArray addObject:myCar];
NSLog(#"This was returned lat from ViewControllerB %ff",[myCar getLatitude]);
NSLog(#"This was returned longi from ViewControllerSlider %ff",[myCar getLongitude]);
NSLog(#"This was returned desp from ViewControllerB %#",[myCar getDesp]);
NSLog(#"This was returned state from ViewControllerSlider %i",[myCar getState]);
lastChk = CarArray.lastObject;
[self writeToTextFile:[NSString stringWithFormat:#"%#%#%#%#%#%#", lastChk.getDesp , #"\n",[NSString stringWithFormat:#"%f", lastChk.getLatitude],
#"\n", [NSString stringWithFormat:#"%f", lastChk.getLongitude], #"\n" ]];
NSLog(#"This was map arraoy count #%i" , [CarArray count]);
for (int i = 0; i < [CarArray count]; i++) {
CheckPoints *current = [CarArray objectAtIndex:i];
if(current.getLatitude != lastChk.getLatitude && current.getLongitude != lastChk.getLongitude){
[current setState:1];
NSString* previousTitle = [NSString stringWithFormat:#"%#%#", #"Checkpoint" ,[NSString stringWithFormat:#"%i", i+1]];
[current setDesp:previousTitle];
}
}
[self addMarkers];
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate{
p = coordinate;
SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"SliderViewController"];
sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentViewController:sliderVC animated:YES completion:NULL];
}
-(void) mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate
{
p = coordinate;
SliderViewController * sliderVC = [self.storyboard instantiateViewControllerWithIdentifier:#"SliderViewController"];
sliderVC.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
sliderVC.modalPresentationStyle = UIModalPresentationCurrentContext;
**[sliderVC setDelegate:self]**
[self presentViewController:sliderVC animated:YES completion:NULL];
}
and
- (IBAction)reset:(id)sender
{
[self writeToTextFile:valueV :valueC];
[self.delegate passData:_uiSlider.value :_circularSlider.currentValue ];
[self dismissViewControllerAnimated:YES completion:nil];
}
Don't create a new instance. What you need is just use delegate.
I want to retrieve the current position and send it with a POST request to a server.
I use mapView.userLocation.location.coordinate but it doesn't work and shows always 0.0 for lat and 0.0 for lng.
This is .h of my controller:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface CustomViewController : UIViewController
<MKMapViewDelegate>
#property NSMutableArray * shops;
#property (strong, nonatomic) IBOutlet UIActivityIndicatorView *loadingIcon;
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#end
and this .m :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_mapView.showsUserLocation = YES;
_mapView.delegate = self;
_shops = [[NSMutableArray alloc] init];
[_loadingIcon startAnimating];
CLLocationCoordinate2D coordinate;
coordinate = _mapView.userLocation.location.coordinate;
NSNumber *lat = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *lng = [NSNumber numberWithDouble:coordinate.longitude];
//here the post method
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:lat,lng, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
.....
NSLog(#"posizione %#", jsonString);
}
in Log I always have 0.0 0.0.
I have this method too:
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation: (MKUserLocation *)userLocation
{
[_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
userLocation.title = #"Posizione attuale";
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2000, 2000);
[_mapView setRegion:region animated:YES];
NSLog(#"lat %f", (double)userLocation.location.coordinate.latitude);
}
and in this case the log shows the current position.
Someone have an idea?
Hello friends i am uploading my code from last few days on the stackoverflow but somwhow i am not getting the thing which i want. Noe once again i am trying this please try to help me out and solve my proplems. Firstly see the code.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import <UIKit/UIKit.h>
#import <GoogleMaps/GoogleMaps.h>
#interface welcomemapViewController : UIViewController
#property (strong, nonatomic) UITextField *txt;
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
welcomeViewController.m
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#import "welcomemapViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kLatestSearchURL [NSURL URLWithString: #"https://maps.googleapis.com/maps/api/place/textsearch/xml?query=Delhi&sensor=true&key=Your API key"]
#interface welcomemapViewController ()
#end
#implementation welcomemapViewController
{
GMSMapView *gmap;
}
#synthesize txt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
GMSCameraPosition *cam = [GMSCameraPosition cameraWithLatitude:30.7343000 longitude:76.7933000 zoom:12];
gmap = [GMSMapView mapWithFrame:CGRectMake(0, 60, 320, 480) camera:cam];
gmap.myLocationEnabled = YES;
gmap.mapType = kGMSTypeHybrid;
gmap.settings.myLocationButton = YES;
gmap.settings.zoomGestures = YES;
gmap.settings.tiltGestures = NO;
gmap.settings.rotateGestures = YES;
[self.view addSubview:gmap];
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(30.751288, 76.780899);
marker.title = #"Sector -16";
marker.snippet = #"Chandigarh";
marker.map = gmap;
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];
CGRect frame2 = CGRectMake(10, 68, 200, 30);
txt =[[UITextField alloc]initWithFrame:frame2];
txt.placeholder = #"Search";
txt.userInteractionEnabled = YES;
txt.keyboardType = UIKeyboardTypeAlphabet;
[txt setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:txt];
// Do any additional setup after loading the view from its nib.
}
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSString *data1 = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"Response data: %#", data1);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* responseResults = [json objectForKey:#"results"];
NSLog(#"Locations are %#", responseResults);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
now in "NSLog(#"Locations are %#", responseResults);" i am getting my values, i simply want to add these values onto the map in the form of pointers with details.
So kindly help me how it should be done. (And kindly help me with the help of codes)
you can do this by using MKPointAnnotation and then add this MKPointAnnotation in you mapview
CLLocationCoordinate2D annotationCoord;
annotationCoord.latitude = #"your Latitude to point on map";
annotationCoord.longitude = #"your Longitude to point on map";;
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = annotationCoord;
annotationPoint.title = #"your title";
annotationPoint.subtitle = #"your subtitle";
[YourmapView addAnnotation:annotationPoint];