Locating markers on the google map - ios

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];

Related

customize marker icon in marker clustering in iOS

Is there any way to change default marker icon in marker clustering?
Here is my code...
- (void)viewDidLoad {
[super viewDidLoad];
// Set up the cluster manager with a supplied icon generator and renderer.
id<GMUClusterAlgorithm> algorithm = [[GMUNonHierarchicalDistanceBasedAlgorithm alloc] init];
id<GMUClusterIconGenerator> iconGenerator = [[GMUDefaultClusterIconGenerator alloc] init];
id<GMUClusterRenderer> renderer = [[GMUDefaultClusterRenderer alloc] initWithMapView:googleMapView
clusterIconGenerator:iconGenerator];
clusterManager = [[GMUClusterManager alloc] initWithMap:googleMapView
algorithm:algorithm
renderer:renderer];
// Register self to listen to both GMUClusterManagerDelegate and
// GMSMapViewDelegate events.
[clusterManager setDelegate:self mapDelegate:self];
}
- (void)loadView {
// Create a GMSCameraPosition that tells the map to display the
_camera = [GMSCameraPosition cameraWithLatitude:29.3117
longitude:47.4818
zoom:8];
googleMapView = [GMSMapView mapWithFrame:CGRectZero camera:_camera];
googleMapView.myLocationEnabled = YES;
googleMapView.settings.compassButton = YES;
googleMapView.settings.myLocationButton = YES;
googleMapView.delegate = self;
self.view = googleMapView;
}
-(void)setLocation:(CLLocation *)location
{
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
[googleMapView animateToLocation:center];
[googleMapView animateToZoom:12];
NSMutableArray *array = [NSMutableArray arrayWithObjects:
#"29.0827,48.1363",
#"29.2679,47.9927",
#"29.348706, 48.092425",
#"29.340925, 48.088477",
#"29.324912, 48.089850",
#"29.330599, 47.990630",
#"29.300364, 47.960589",
#"29.271917, 47.918017",
#"29.3032,47.936", nil];
//remove all clusters before adding clusters
[clusterManager clearItems];
for (int i = 0; i < [array count]; i++)
{
center = CLLocationCoordinate2DMake ([[array[i] componentsSeparatedByString:#","][0] floatValue], [[array[i] componentsSeparatedByString:#","][1] floatValue]);
// Add items to the cluster manager.
NSString *name = nil;//[NSString stringWithFormat:#"Item %d", i];
id<GMUClusterItem> item =[[POIItem alloc] initWithPosition:center
name:name];
[clusterManager addItem:item];
}
// Call cluster() after items have been added
// to perform the clustering and rendering on map.
[clusterManager cluster];
}
Please guide me...
I see that you used google-maps-ios-utils. The problem is that there is no API for change marker's icon yet. You can only do it directly in the code of the library. I've pasted my custom code inside the method
- (GMSMarker *)markerWithPosition:(CLLocationCoordinate2D)position
from:(CLLocationCoordinate2D)from
userData:(id)userData
clusterIcon:(UIImage *)clusterIcon
animated:(BOOL)animated{
//...
if (clusterIcon != nil) {
marker.icon = clusterIcon;
marker.groundAnchor = CGPointMake(0.5, 0.5);
} else {
if([[marker.userData class] isSubclassOfClass:[POIItem class]]){
POIItem *item = (POIItem *)marker.userData;
MarkerIcon* markerView = (MarkerIcon *)[[NSBundle mainBundle] loadNibNamed:#"MarkerIcon" owner:marker options:nil][0];
marker.iconView = markerView;
marker.groundAnchor = CGPointMake(0.5, 0.5);
}
}
}
It is not a good way to change the code like this. But I could not find better solution for that moment.
I have already sovled this question.
I used googleMaps Api version:8.1.
Here is my code...
#import "Clustering/GMUClusterItem.h"
// Point of Interest Item which implements the GMUClusterItem protocol.
#interface POIItem : NSObject<GMUClusterItem>
#property(nonatomic, readonly) CLLocationCoordinate2D position;
#property(nonatomic, readonly) NSString *name;
- (instancetype)initWithPosition:(CLLocationCoordinate2D)position name:(NSString *)name;
#end
1.creat the map.
#interface BasicViewController ()<GMUClusterManagerDelegate, GMSMapViewDelegate,
GMUClusterRendererDelegate>
#end
typedef NS_ENUM(NSInteger, ClusterAlgorithmMode) {
kClusterAlgorithmGridBased,
kClusterAlgorithmQuadTreeBased,
};
#implementation BasicViewController {
GMSMapView *_mapView;
GMUClusterManager *_clusterManager;
}
- (void)loadView {
//创建地图
GMSCameraPosition *camera =
[GMSCameraPosition cameraWithLatitude:kCameraLatitude longitude:kCameraLongitude zoom:10];
_mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = _mapView;
}
2.creat GMUClusterManager object.
- (void)viewDidLoad {
[super viewDidLoad];
//添加标注算法方式
id<GMUClusterAlgorithm> algorithm = [self algorithmForMode:kClusterAlgorithmQuadTreeBased];
//标注icon
id<GMUClusterIconGenerator> iconGenerator = [self iconGeneratorWithImages];//[self defaultIconGenerator];
// CustomClusterIconGenerator *iconGenerator = [[CustomClusterIconGenerator alloc] init];
GMUDefaultClusterRenderer *renderer =
[[GMUDefaultClusterRenderer alloc] initWithMapView:_mapView
clusterIconGenerator:iconGenerator];
renderer.delegate = self;
_clusterManager =
[[GMUClusterManager alloc] initWithMap:_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];
UIBarButtonItem *removeButton =
[[UIBarButtonItem alloc] initWithTitle:#"Remove"
style:UIBarButtonItemStylePlain
target:self
action:#selector(removeClusterManager)];
self.navigationItem.rightBarButtonItems = #[ removeButton ];
}
3.in method :
/*You can set marker image here
if [marker class] is POIItem.
*/
- (void)renderer:(id<GMUClusterRenderer>)renderer willRenderMarker:(GMSMarker *)marker {
if ([marker.userData isKindOfClass:[POIItem class]]) {
POIItem *item = marker.userData;
marker.title = item.name;
******marker.icon = [UIImage imageNamed:#"register"];******
}
}

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

SingleTapOnMap method not calling in iphone

I am using below piece of code using to interact with MBTiles. But singleTapOnMap method is not calling when i run it on iphone. I also added Trailer which is working on TileMill, but not on iPhone. Whether i have gone wrong anywhere?
//ViewController.h
#interface ViewController : UIViewController<RMMapViewDelegate>
#end
//ViewController.m
- (void)viewDidLoad
{
RMMBTilesSource *offlineSource = [[RMMBTilesSource alloc] initWithTileSetResource:#"MYMAP" ofType:#"mbtiles"];
RMMapView *mapView = [[RMMapView alloc] initWithFrame:self.view.bounds andTilesource:offlineSource];
mapView.zoom = 2;
mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
mapView.adjustTilesForRetinaDisplay = YES; // these tiles aren't designed specifically for retina, so make them legible
[self.view addSubview:mapView];
}
#pragma mark -
- (void)singleTapOnMap:(RMMapView *)mapView at:(CGPoint)point
{
[mapView removeAllAnnotations];
RMMapBoxSource *source = (RMMapBoxSource *)mapView.tileSource;
NSLog(#"You tapped at %f, %f", [mapView pixelToCoordinate:point].latitude, [mapView pixelToCoordinate:point].longitude);
if ([source conformsToProtocol:#protocol(RMInteractiveSource)] && [source supportsInteractivity])
{
NSString *formattedOutput = [source formattedOutputOfType:RMInteractiveSourceOutputTypeTeaser
forPoint:point
inMapView:mapView];
if (formattedOutput && [formattedOutput length])
{
// parse the country name out of the content
//
NSUInteger startOfCountryName = [formattedOutput rangeOfString:#"<strong>"].location + [#"<strong>" length];
NSUInteger endOfCountryName = [formattedOutput rangeOfString:#"</strong>"].location;
NSString *countryName = [formattedOutput substringWithRange:NSMakeRange(startOfCountryName, endOfCountryName - startOfCountryName)];
// parse the flag image out of the content
//
NSUInteger startOfFlagImage = [formattedOutput rangeOfString:#"base64,"].location + [#"base64," length];
NSUInteger endOfFlagImage = [formattedOutput rangeOfString:#"\" style"].location;
UIImage *flagImage = [UIImage imageWithData:[NSData dataFromBase64String:[formattedOutput substringWithRange:NSMakeRange(startOfFlagImage, endOfFlagImage)]]];
RMAnnotation *annotation = [RMAnnotation annotationWithMapView:mapView coordinate:[mapView pixelToCoordinate:point] andTitle:countryName];
annotation.userInfo = flagImage;
[mapView addAnnotation:annotation];
[mapView selectAnnotation:annotation animated:YES];
}
}
}
- (RMMapLayer *)mapView:(RMMapView *)mapView layerForAnnotation:(RMAnnotation *)annotation
{
RMMarker *marker = [[RMMarker alloc] initWithMapBoxMarkerImage:#"embassy"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 32)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = annotation.userInfo;
marker.leftCalloutAccessoryView = imageView;
marker.canShowCallout = YES;
return marker;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
You have to assign the delegate protocol:
mapView.delegate = self;

Play audio from Parse via UIButton

I've been working on an app that allows audio to be played from Parse (like a social network), but am having trouble getting the code to not have errors.
My .h file
#import <UIKit/UIKit.h>
#interface TalklineViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIScrollView *wallScroll;
#end
My .m file
#interface TalklineViewController ()
#property (nonatomic, retain) NSArray *wallAudioArray;
#end
#implementation TalklineViewController
#synthesize wallAudioArray = _wallAudioArray;
#synthesize wallScroll = _wallScroll;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)getWallAudio
{
//Prepare the query to get all the images in descending order
//1
PFQuery *query = [PFQuery queryWithClassName:#"AudioObject"];
//2
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//3
if (!error) {
//Everything was correct, put the new objects and load the wall
self.wallAudioArray = nil;
self.wallAudioArray = [[NSArray alloc] initWithArray:objects];
[self loadWallViews];
} else {
//4
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
}
-(void)loadWallViews
{
//Clean the scroll view
for (id viewToRemove in [self.wallScroll subviews]){
if ([viewToRemove isMemberOfClass:[UIView class]])
[viewToRemove removeFromSuperview];
}
//For every wall element, put a view in the scroll
int originY = 10;
for (PFObject *audioObject in self.wallAudioArray){
//1
//Build the view with the image and the comments
UIView *wallAudioView = [[UIView alloc] initWithFrame:CGRectMake(10, originY, self.view.frame.size.width - 20 , 300)];
//2
//Add the image
PFFile *audio = (PFFile *)[audioObject objectForKey:#"audio"];
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
userAudio.frame = CGRectMake(0, 0, wallAudioView.frame.size.width, 200);
[wallAudioView addSubview:userAudio];
//3
//Add the info label (User and creation date)
NSDate *creationDate = audioObject.createdAt;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm dd/MM yyyy"];
//4
UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, wallAudioView.frame.size.width,15)];
infoLabel.text = [NSString stringWithFormat:#"Uploaded by: %#, %#", [audioObject objectForKey:#"user"], [df stringFromDate:creationDate]];
infoLabel.font = [UIFont fontWithName:#"Arial-ItalicMT" size:9];
infoLabel.textColor = [UIColor whiteColor];
infoLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:infoLabel];
//5
//Add the comment
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 240, wallAudioView.frame.size.width, 15)];
commentLabel.text = [audioObject objectForKey:#"comment"];
commentLabel.font = [UIFont fontWithName:#"ArialMT" size:13];
commentLabel.textColor = [UIColor whiteColor];
commentLabel.backgroundColor = [UIColor clearColor];
[wallAudioView addSubview:commentLabel];
//6
[self.wallScroll addSubview:wallAudioView];
originY = originY + wallAudioView.frame.size.width + 20;
}
//7
//Set the bounds of the scroll
self.wallScroll.contentSize = CGSizeMake(self.wallScroll.frame.size.width, originY);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The problem line is:
UIButton *userAudio = [[UIButton alloc][[UIButton buttonWithType:UIButtonTypeSystem audioWithData:audio.getData]];
Any help is greatly appreciated!
UIButton doesn't have an audioWithData method, so that's the biggest issue here; instead, add a target to the button to play the audio with a seperate method:
UIButton *userAudio = [UIButton buttonWithType:UIButtonTypeSystem];
[userAudio setFrame:CGRectMake(20, 20, 100, 44)];
[userAudio setTitle:#"Play Audio!" forState:UIControlStateNormal];
[userAudio addTarget:self action:#selector(playAudio) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:userAudio];
- (void)playAudio
{
// Your audio data and playing code here
// audio.getData
}

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