How to detect Marker's location after draggable - objective-c

I'm trying to get Marker's location after draggable in Google Map. Current is I can add Marker in Google Map according to current location of device in snippet. Now, what I want is try to get Marker's location based on draggable position.
placemark = [placemarks lastObject];
CLLocationCoordinate2D position = { [latitude doubleValue], [longitude doubleValue] };
mymarker = [GMSMarker markerWithPosition:position];
mymarker.title = [NSString stringWithFormat:#"%#", placemark.thoroughfare];
mymarker.appearAnimation = YES;
mymarker.flat = YES;
mymarker.snippet = [NSString stringWithFormat:#"%# %#, %# %#", placemark.locality, placemark.administrativeArea, placemark.postalCode, placemark.country];
mymarker.map = _mapView;
mymarker.draggable = true;

Give this a try
-(void)mapView:(GMSMapView *)mapView didEndDraggingMarker:(GMSMarker *)marker{
NSLog(#"New location of marker: Lat: %f, Long: %f", marker.position.latitude, marker.position.longitude);
}

Related

How to Take screen of desktop wallpaper without icons and windows for multiple screens?

In my cocoa application i want to take the screenshot of desktop wallpaper for Multiple screens i've found this link with this i made for single screen However, i am finding difficult for multiple screens. So how would i do it for multiple screens?
here is my code
- (NSImage*) desktopAsImageWithScreen:(NSScreen *)screen {
NSDictionary *deviceDescription = [screen deviceDescription];
CFMutableArrayRef windowIDs = CFArrayCreateMutable(NULL, 0, NULL);
CFArrayRef allWindowIDs = CGWindowListCreate(kCGWindowListOptionOnScreenBelowWindow, kCGDesktopIconWindowLevel);
NSLog(#"min window level: %d", kCGMinimumWindowLevel);
NSLog( #"looking for windows on level: %d", kCGDesktopWindowLevel );
NSLog( #"NOt actually looking for windows on level: %d", kCGMinimumWindowLevel );
NSLog( #"NOt actually looking for windows on the dock level: %d", kCGDockWindowLevel );
if (allWindowIDs)
{
CFArrayRef windowDescs = CGWindowListCreateDescriptionFromArray(allWindowIDs);
for (CFIndex idx=0; idx<CFArrayGetCount(windowDescs); idx++)
{
CFDictionaryRef dict = CFArrayGetValueAtIndex(windowDescs, idx);
CFStringRef ownerName = CFDictionaryGetValue(dict, kCGWindowOwnerName);
NSLog(#"owner name = %#", ownerName);
if (CFStringCompare(ownerName, CFSTR("Dock"), 0) == kCFCompareEqualTo )
{
// the Dock level has the dock and the desktop picture
CGRect windowBounds;
BOOL success = CGRectMakeWithDictionaryRepresentation(
(CFDictionaryRef)(CFDictionaryGetValue(dict, kCGWindowBounds)),
&windowBounds);
NSRect screenBounds = screen.frame;
CFNumberRef windowLayer = CFDictionaryGetValue(dict, kCGWindowLayer);
//CFDictionaryGetValue(dict, kCGWindowBounds)
NSLog(#"window bounds %f, %f, matches screen bounds? %d, on level %#",
windowBounds.size.width,
windowBounds.size.height,
CGRectEqualToRect(windowBounds, screenBounds),
windowLayer
);
NSNumber* ourDesiredLevelNumber = [NSNumber numberWithInt: kCGDesktopWindowLevel - 1];
if ( CGRectEqualToRect(windowBounds, screenBounds) && [ourDesiredLevelNumber isEqualToNumber: (__bridge NSNumber * _Nonnull)(windowLayer)] )
CFArrayAppendValue(windowIDs, CFArrayGetValueAtIndex(allWindowIDs, idx));
}
}
CFRelease(windowDescs);
CFRelease(allWindowIDs);
}
CGImageRef cgImage = CGWindowListCreateImageFromArray( screen.frame, windowIDs, kCGWindowImageDefault);
// Create a bitmap rep from the image...
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
// Create an NSImage and add the bitmap rep to it...
NSImage *image = [[NSImage alloc] init];
[image addRepresentation:bitmapRep];
//[bitmapRep release];
return image;
}
Any Suggestions?
Thanks in Advance!

Why I am not able to get Latitude and longitude on real device in Objective C

I am new in iOS and I am facing problem to get current Latitude and Longitude on the real device where as I am able to get latitude and Longitude on simulator.
My code is like this
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//Configure Accuracy depending on your needs, default is kCLLocationAccuracyBest
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
locationManager.distanceFilter = kCLDistanceFilterNone; // meters
[locationManager startUpdatingLocation];
Currentlatitude = locationManager.location.coordinate.latitude;
Currentlongitude = locationManager.location.coordinate.longitude;
NSLog(#"Latitude =%f",Currentlatitude);
NSLog(#"Longitude =%f",Currentlongitude);
CheckString=#"2";
// Your location from latitude and longitude
CLLocation *location = [[CLLocation alloc] initWithLatitude:Currentlatitude longitude:Currentlongitude];
// Call the method to find the address
[self getAddressFromLocation:location completionHandler:^(NSMutableDictionary *d) {
NSLog(#"address informations : %#", d);
// NSLog(#"formatted address : %#", [placemark.addressDictionary valueForKey:#"FormattedAddressLines"]);
NSLog(#"Street : %#", [d valueForKey:#"Street"]);
NSLog(#"ZIP code : %#", [d valueForKey:#"ZIP"]);
NSLog(#"City : %#", [d valueForKey:#"City"]);
CityNameCurrent=[d valueForKey:#"City"];
// etc.
} failureHandler:^(NSError *error) {
NSLog(#"Error : %#", error);
}];
- (void)getAddressFromLocation:(CLLocation *)location completionHandler:(void (^)(NSMutableDictionary *placemark))completionHandler failureHandler:(void (^)(NSError *error))failureHandler
{
NSMutableDictionary *d = [NSMutableDictionary new];
CLGeocoder *geocoder = [CLGeocoder new];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (failureHandler && (error || placemarks.count == 0)) {
failureHandler(error);
} else {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if(completionHandler) {
completionHandler(placemark.addressDictionary);
}
}
}];
}
In ViewDidLod()
mapViewMap.delegate=self;
mapViewMap.myLocationEnabled=YES;
locationtbl.hidden=YES;
if (nil == locationManager)
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
//Configure Accuracy depending on your needs, default is kCLLocationAccuracyBest
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// Set a movement threshold for new events.
locationManager.distanceFilter = kCLDistanceFilterNone; // meters
[locationManager startUpdatingLocation];
Currentlatitude = locationManager.location.coordinate.latitude;
Currentlongitude = locationManager.location.coordinate.longitude;
NSLog(#"Latitude =%f",Currentlatitude);
NSLog(#"Longitude =%f",Currentlongitude);
mapViewMap.settings.myLocationButton = YES;
mapViewMap.settings.scrollGestures = YES;
mapViewMap.settings.zoomGestures = YES;
mapViewMap.settings.tiltGestures=YES;
mapViewMap.settings.rotateGestures=NO;
mapViewMap.settings.compassButton = YES;
I am not getting what I am doing wrong.Please help.Thanks in Advance!
The simulator doesn't have to wait for a fix before generating a location. The device does. You have to implement a delegate for the location manager and wait for the delegate to be called with an update.
You need to implement CLLocationManager delegate method didUpdateLocations, it is where you get location updates.
You can do it like this.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
// latest location
self.currentLocation = [locations lastObject];
float longitude = self.currentLocation.coordinate.longitude;
float latitude = self.currentLocation.coordinate.latitude;
// Here you can perform operations with your location coordinates
}
You also need to add following entries in your .plist file based on your location need.
NSLocationWhenInUseUsageDescription
or
NSLocationAlwaysUsageDescription
And request the permission for location usage by calling
[locationManager requestWhenInUseAuthorization];
or
[locationManager requestAlwaysAuthorization]
Documentation link Location and Maps Programming Guide
You also need to add one (or both) of the following keys to you plist:
NSLocationWhenInUseUsageDescription
or
NSLocationAlwaysUsageDescription
and call correspondingly either
[self.locationManager requestWhenInUseAuthorization]
or
[self.locationManager requestAlwaysAuthorization]

kindly advice me to display x number of annotation points in mkmap

Good morning, I am very new to objective-c now I am developing my first app. It's a vehicle tracking app. I received the x-number of lat & long from the json service. Now I displayed a single annotation but I need to display all the annotation points which i received from the service here I search for a whole day to find this but am fails to find displaying x-num of annotations. So kindly advice me by using some sample codes. Thanks in Advance... My code is..
- (void)viewDidLoad
{
[super viewDidLoad];
//MAP VIEW WebService
NSString *urlMapString=[NSString stringWithFormat:#"http://www.logix.com/logix_webservice/map.php?format=json&truckno=%#",nam2];
NSURL *urlMap=[NSURL URLWithString:urlMapString];
NSData *dataMap=[NSData dataWithContentsOfURL:urlMap];
NSError *errorMap;
NSDictionary *jsonMap = [NSJSONSerialization JSONObjectWithData:dataMap options:kNilOptions error:&errorMap]; NSArray *resultsMap = [jsonMap valueForKey:#"posts"];
NSArray *resMap = [resultsMap valueForKey:#"post"];
NSArray *latitudeString=[resMap valueForKey:#"latitude"];
if([resMap count]){
NSString *latOrgstring = [latitudeString objectAtIndex:0];
double latitude=[latOrgstring doubleValue];
NSArray *longitudeString=[resMap valueForKey:#"longitude"];
NSString *longOrgstring = [longitudeString objectAtIndex:0];
double longitude=[longOrgstring doubleValue];
NSString *ignation=[[resMap valueForKey:#"ignition"]objectAtIndex:0];
i=[ignation intValue];
//MAP VIEW Point
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude=latitude;
center.longitude=longitude;
//Span
MKCoordinateSpan span;
span.latitudeDelta=0.01f;
span.longitudeDelta=0.01f;
myRegion.center=center;
myRegion.span=span;
//Set our mapView
[MapViewC setRegion:myRegion animated:YES];
//Annotation
//1.create coordinate for use with the annotation
CLLocationCoordinate2D wimbLocation;
wimbLocation.latitude=latitude;
wimbLocation.longitude=longitude;
Annotation * myAnnotation= [Annotation alloc];
CLLocation *someLocation=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:someLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSDictionary *dictionary = [[placemarks objectAtIndex:0] addressDictionary];
addressOutlet=[dictionary valueForKey:#"Street"];
City=[dictionary valueForKey:#"City"];
State=[dictionary valueForKey:#"State"];
myAnnotation.coordinate=wimbLocation;
if (addressOutlet!=NULL&&City!=NULL)
{
myAnnotation.title=addressOutlet;
myAnnotation.subtitle=[NSString stringWithFormat:#"%#,%#", City, State];
}
else if (addressOutlet==NULL&&City!=NULL)
{
myAnnotation.title=City;
myAnnotation.subtitle=[NSString stringWithFormat:#"%#,%#", City, State];
}
else if (addressOutlet!=NULL&&City==NULL)
{
myAnnotation.title=addressOutlet;
myAnnotation.subtitle=[NSString stringWithFormat:#"%#", State];
}
else if(addressOutlet==NULL&&City==NULL)
{
myAnnotation.title=State;
myAnnotation.subtitle=[NSString stringWithFormat:#"%#",State];
}
[self.MapViewC addAnnotation:myAnnotation];
}];
}
}
Please make an individual class and use by importing .
Now use
-(id)initWithCoordinate:(CLLocationCoordinate2D)c;
and its .m file
-(id)initWithCoordinate:(CLLocationCoordinate2D)c
{
coordinate=c;
}
Now call this class anywhere and call this method and send your location coordinates.
and then add its objects into NSArray.
Now call [YourMapView addAnnotations:arrayOfAnnotations];
You will get it what you want.It works in my case I hope you will find it supportive.
Now add annotations on mapView:
-(MKAnnotationView *) mapView:(MKMapView *)mapV
viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[pinAnnotation class]])
{
static NSString *defaultPinID = #"com.ABC.pin";//Your unique identifier anything
MKAnnotationView *pinView = nil;
if(!pinView)
{
pinView = (MKAnnotationView *)
[self.mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
pinView = [[MKAnnotationView alloc] initWithAnnotation:
annotation reuseIdentifier:defaultPinID] ;
return pinView;
}
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView* pin =
(MKAnnotationView*) [mapV dequeueReusableAnnotationViewWithIdentifier:
AnnotationViewID];
if ( pin == nil ) {
pin = [(MKAnnotationView*) [MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier: AnnotationViewID] ;
pin.canShowCallout = YES;
}
else
{
[pin setAnnotation: annotation];
}
((MKUserLocation *)annotation).title = #"You are here";
return pin;
}

Annotations in MapView

I have this code:
-(void)handleLongPressGesture:(UIGestureRecognizer*)sender {
NSNumber* existingpoints = [[NSNumber alloc]init];
existingpoints =[NSNumber numberWithInt:0];
// This is important if you only want to receive one tap and hold event
if (sender.state == UIGestureRecognizerStateEnded)
{
[self.mapView removeGestureRecognizer:sender];
}
else {
do {
int z = 1;
existingpoints =[NSNumber numberWithInt:z];
// Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map
CGPoint point = [sender locationInView:self.mapView];
CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
// Then all you have to do is create the annotation and add it to the map
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init]; annotationPoint.coordinate = locCoord;
NSString *latitude = [[NSString alloc] initWithFormat:#"%f",locCoord.latitude];
NSString *longitude = [[NSString alloc] initWithFormat:#"%f", locCoord.longitude];
annotationPoint.title = #"Event";
annotationPoint.subtitle = [NSString stringWithFormat:#"%# & %#", latitude, longitude];
[mapView addAnnotation:annotationPoint];
[[NSUserDefaults standardUserDefaults]setObject:latitude forKey:#"FolderLatitude"];
[[NSUserDefaults standardUserDefaults]setObject:longitude forKey:#"FolderLongitude"];
} while ([existingpoints intValue] == 0);
}
}
...but the problem is that when I hold, and then drag more than one pin is added. I want to add only one pin. So I tried the do method but it doesn't work. I can't understand, because when I executed the code I turn the value of the NSNumber to 1, and the while says = 0 to run the code.
Please Help!!
Your current code is prone to have quite a number of memory leaks. For example:
NSNumber* existingpoints = [[NSNumber alloc] init];
existingpoints = [NSNumber numberWithInt:0];
Is leaking because you leave the first instance of existingpoints with retain value of 1 and not freeing it anywhere. Unless you're using ARC. You can optimize the above code with just one instruction:
NSNumber* existingpoints = [NSNumber numberWithInt:0];
And retain it if you need to keep it somewhere (but i belive it's not the case).
Analyzing the code, I'd recommend NOT to use existingpoints as an NSNumber. Use an NSInteger instead (which is not an object, just a typedef to long).
Here's my rewritten code:
-(void)handleLongPressGesture:(UIGestureRecognizer*)sender {
NSInteger existingpoints = 0;
// This is important if you only want to receive one tap and hold event
if (sender.state == UIGestureRecognizerStateEnded) {
[self.mapView removeGestureRecognizer:sender];
}
else {
do {
int z = 1;
existingpoints = z;
// Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map
CGPoint point = [sender locationInView:self.mapView];
CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
// Then all you have to do is create the annotation and add it to the map
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = locCoord;
NSString *latitude = [NSString stringWithFormat:#"%f",locCoord.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", locCoord.longitude];
annotationPoint.title = #"Event";
annotationPoint.subtitle = [NSString stringWithFormat:#"%# & %#", latitude, longitude];
[mapView addAnnotation:annotationPoint];
[[NSUserDefaults standardUserDefaults] setObject:latitude forKey:#"FolderLatitude"];
[[NSUserDefaults standardUserDefaults] setObject:longitude forKey:#"FolderLongitude"];
[annotationPoint release]; // Remove this if you're using ARC.
} while (existingpoints == 0);
}
}
Note that I've also changed the code for creating latitude and longitude for not to create any memory leaks when using ARC.
EDIT:
Further analyzing your code, I don't see why this method would be dropping two pins at once. Maybe you could check if your method is not being called twice?
More: Why do you have a do/while loop if you just want it to run once? (but maybe you're just paving your ground to further ahead)

Objective C: Getting 'Invalid Initializer Error' when setting CLLocationCoordinate2D location

I am trying to find and set the location as shown below but I keep getting the error 'Invalid Initializer'
CLLocationCoordinate2D location =[self.mapView addressLocation];
Where addressLocation method is as show below
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
Can you advise why I am getting the 'Invalid initializer' error? I have already imported the corelocation location framework and also imported the header files. So not sure what is wrong.
You are invoking [self.mapView addressLocation]. Shouldn't it be [self addressLocation]? I'm presuming mapView is the MKMapView in your class and doesn't have any addressLocation method.