So I followed this guide on how to add a Google map to an iOS application and it all works fine. But what I want to do is assign the map, not to self.view but a custom view I dragged out on to the storyboard inside(?) the other view, because when adding the map to self.view I can't add other elements, like buttons, or well, I probably can but I don't know how.
Code:
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
// Set up the startposition for the camera when the app first starts.
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:59.34702 longitude:18.04053 zoom:10];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.view = mapView_;
So i created a UIView inside the view currently containing the map and ctrl dragged it to create an outlet called mapView in that viewController. So i changed the line of code from
self.view = _mapView;
to
self.mapView = _mapView;
but this does not seem to work at all, just blank. Both self.view and self.mapsView are instances of UIView, so why does this not work?
Update:
This is what my viewDidLoad looks like atm:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.mapView addSubview:mapView_];
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
// Standard cameraposition
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:59.34702 longitude:18.04053 zoom:10];
mapView_ = [GMSMapView mapWithFrame:self.mapView.frame camera:camera];
self.mapView = mapView_;
}
Do the following:
Change your custom view Class to GMSMapView in the identity inspector of IB
create outlet mapView to this custom view in you view controller (pay attention that outlet type is also GMSMapView)
So now when you start your app this instance will be created, and it will display default location on the map (near London). Now you only need to create a camera and add it to the map object. Add this code in your ViewDidLoad method:
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:45.24 longitude:19.84 zoom:6];
// set camera location to Novi Sad, Serbia :-)
[self.mapView setCamera:camera]; // set the camera to map
Thats it, you do not need instance variable mapView_ from Google sample code, nor any other code from Google sample. Enjoy!
Try this in your project:
//
// testViewController.m
// maps
//
// Created by Millén on 2013-02-25.
// Copyright (c) 2013 JamWeb. All rights reserved.
//
#import "testViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface testViewController ()
#property(nonatomic, strong) GMSMapView *gMapView;
#end
#implementation testViewController {
CLLocation *oldLocation;
}
-(void)loadView
{
CLLocationDegrees lat = 59.34702;
CLLocationDegrees lon = 18.04053;
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:10];
self.gMapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.gMapView.myLocationEnabled = YES;
self.view = self.gMapView;
[self updateLocation];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Start locationmanager
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
- (IBAction)updateLocation {
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
/*
if(!oldLocation)
{
oldLocation = location;
}
if (![location isEqual:oldLocation]) {
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude: location.coordinate.latitude
longitude: location.coordinate.longitude
zoom:7];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.myLocationEnabled = YES;
self.view = mapView_;
oldLocation = location;
[locationManager stopUpdatingLocation];
}
*/
NSLog(#"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
In your code you have:
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
CGRectZero will make its size zero. You should use self.mapView.frame instead.
Also need to add add mapView_ as subview of mapView:
[self.mapView addSubview:mapView_];
Related
For some reason when I launch my app it does everything correctly except show the user as blue dot on the map. It zooms in to the users current location, just no dot. Any help would be greatly appreciated.
I've added code and screenshots below for resources.
FrontViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface FrontViewController : UIViewController <CLLocationManagerDelegate>
{
CLLocationManager *objLocationManager;
double latitude_UserLocation, longitude_UserLocation;
}
#property (weak, nonatomic) IBOutlet MKMapView *objMapView;
#end
FrontViewController.m
#import "FrontViewController.h"
#import "SWRevealViewController.h"
#interface FrontViewController()
// Private Methods:
- (IBAction)pushExample:(id)sender;
#end
#implementation FrontViewController
#synthesize objMapView;
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadUserLocation];
//self.title = NSLocalizedString(#"Front View", nil);
SWRevealViewController *revealController = [self revealViewController];
[revealController panGestureRecognizer];
[revealController tapGestureRecognizer];
[self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];
UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"reveal-icon.png"]
style:UIBarButtonItemStyleBordered target:revealController action:#selector(revealToggle:)];
self.navigationItem.leftBarButtonItem = revealButtonItem;
UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"BSEEK-Logo.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIView* titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 84, 84)];
imageView.frame = titleView.bounds;
[titleView addSubview:imageView];
self.navigationItem.titleView = titleView;
}
- (IBAction)pushExample:(id)sender
{
UIViewController *stubController = [[UIViewController alloc] init];
stubController.view.backgroundColor = [UIColor whiteColor];
[self.navigationController pushViewController:stubController animated:YES];
}
- (void) loadUserLocation
{
objLocationManager = [[CLLocationManager alloc] init];
objLocationManager.delegate = self;
objLocationManager.distanceFilter = kCLDistanceFilterNone;
objLocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
if ([objLocationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
[objLocationManager requestWhenInUseAuthorization];
}
[objLocationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0)
{
CLLocation *newLocation = [locations objectAtIndex:0];
latitude_UserLocation = newLocation.coordinate.latitude;
longitude_UserLocation = newLocation.coordinate.longitude;
[objLocationManager stopUpdatingLocation];
[self loadMapView];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
[objLocationManager stopUpdatingLocation];
}
- (void) loadMapView
{
CLLocationCoordinate2D objCoor2D = {.latitude = latitude_UserLocation, .longitude = longitude_UserLocation};
MKCoordinateSpan objCoorSpan = {.latitudeDelta = 0.2, .longitudeDelta = 0.2};
MKCoordinateRegion objMapRegion = {objCoor2D, objCoorSpan};
[objMapView setRegion:objMapRegion];
}
#end
Project Files
MKMapView has a showsUserLocation property. It looks like you need to turn that on.
You can set that property in code, but if your map view is created in a storyboard scene you can just check the User Location box in the storyboard editor:
Also: Make sure you have the appropriate key in your Info.plist to allow the app to access the user's location, and that you've granted the app appropriate permission on the device. (You can check in Settings->Privacy->Location Services.) If the app doesn't have permission to get the location, the map won't show it even if showsUserLocation is enabled.
I done the task on Mapkit to find the currentLocation by using below code. Now I want to display the current location address at the annotation pain.How to cal the geo coding method for displaying the current location address.latitude and longitude values?
#import "MapKitViewController.h"
#import "ViewController.h"
#define METERS_MILE 1609.344
#define METERS_FEET 3.28084
#interface MapKitViewController ()<CLLocationManagerDelegate,MKMapViewDelegate >
#end
#implementation MapKitViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// _mapView.delegate = self;
locationManager =[[CLLocationManager alloc] init];
[[self mapView ] setShowsUserLocation:YES];
[locationManager setDelegate:self];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
NSLog(#" startUpdatingLocation");
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *location=locations.lastObject;
[[self latitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.latitude]];
[[self longnitudeValue] setText:[NSString stringWithFormat:#"%.6f",location.coordinate.longitude]];
// [[self altitudeValue] setText:[NSString stringWithFormat:#"%.2f feet",location.altitude*METERS_FEET]];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2*METERS_MILE, 2*METERS_MILE);
[[self mapView] setRegion:viewRegion animated:YES];
MKPointAnnotation *point=[[MKPointAnnotation alloc]init];
point.coordinate=location.coordinate;
[self.mapView addAnnotation:point];
point.title=#"this is my place";
NSLog(#"I got the point");
NSLog(#"didUpdateLocations");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#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
For display current location on map use this..
MKPointAnnotation *annonation = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D mycordinate;
mycordinate.latitude = [self.strlog floatValue];
mycordinate.longitude =[self.strlat floatValue];
annonation.coordinate = mycordinate;
[self.mapview addAnnotation:annonation];
I have no issues displaying a users current location, but I am having trouble trying to zoom to it. I have found a few solutions from other posts here, but nothing seems to be working. Advice is appreciated as it is highly likely that I am missing something simple.
Here is what I have so far:
#import CoreLocation;
#interface ViewController () <CLLocationManagerDelegate>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Get authorization
CLLocationManager * locationManager = [[CLLocationManager alloc] init];
// Check before requesting, otherwise it might crash older versions of ios
if ([locationManager respondsToSelector:#selector(requestWhenInUseAuthorization)]) {
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[locationManager requestWhenInUseAuthorization];
}
self.mapView.showsUserLocation = YES;
self.mapView = [[MKMapView alloc] init];
self.mapView.delegate = self;
self.mapView.scrollEnabled = YES;
self.mapView.zoomEnabled = YES;
self.mapView.userTrackingMode = YES;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//CLLocationCoordinate2D loc = [userLocation coordinate];
//MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
//[self.mapView setRegion:region animated:YES];
//Zoom map to users current location
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.00001;
span.longitudeDelta = 0.00001;
CLLocationCoordinate2D location = mapView.userLocation.coordinate;
region.span = span;
region.center = location;
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
#end
I did something like this
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
if (!self.initialLocation) {
self.initialLocation = userLocation.location;
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;
[mapView setRegion:mapRegion animated: YES];
}
}
self.initialLocation is an instance of CLLocation. This method constantly updates the user's current location and so what I would do is check to see if it is nil, which it should be off the start and then run the code to zoom in. After the first time, self.initialLocation will never be nil.
if you would constantly like to zoom into the the user's current location...get rid of the if statement.
EDIT
Set this in your .h file for self.initialLocation
#property (strong, nonatomic) CLLocation *initialLocation;
EDIT 2
Remove this line
self.mapView = [[MKMapView alloc] init];
No need to re-initialize your IBOulet
I'm trying to get a MoPub banner ad to appear. I've created a UIViewController, and put the MoPub code into the View did load as thus..
- (id)init
{
self = [super init];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// ... your other -viewDidLoad code ...
self.adView = [[MPAdView alloc] initWithAdUnitId:#"ID HERE"
size:MOPUB_BANNER_SIZE];
self.adView.delegate = self;
CGRect frame = self.adView.frame;
CGSize size = [self.adView adContentViewSize];
frame.origin.y = [[UIScreen mainScreen] applicationFrame].size.height - size.height;
self.adView.frame = frame;
[self.view addSubview:self.adView];
[self.adView loadAd];
//[super viewDidLoad];
}
#pragma mark - <MPAdViewDelegate>
- (UIViewController *)viewControllerForPresentingModalView {
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
And in my AppDelegate I'm setting everything up like this (it's a Sparrow game)
//setup Sparrow
CGRect screenBounds = [UIScreen mainScreen].bounds;
_window = [[UIWindow alloc] initWithFrame:screenBounds];
_gcViewController = [[UIViewController alloc]init];
_viewController = [[SPViewController alloc] init];
[_viewController startWithRoot:[Game class] supportHighResolutions:YES doubleOnPad:YES];
_viewController.multitouchEnabled = YES;
[_window setRootViewController:_viewController];
adViewController = [[AdViewController alloc]init];
[_window addSubview:adViewController.view];
[_window addSubview:_gcViewController.view];
[_window makeKeyAndVisible];
And in the console I seem to be getting the correct msgs as this...
Looking for custom event class named MPHTMLBannerCustomEvent. MOPUB:
Loading MoPub HTML banner MOPUB: MoPub HTML banner did load
But I can't see anything on the screen in the simulator, any ideas?
I have some problems with adding annotations when the user touch the map.
I'm using UIGestureRecognizer to detect the user's touch.
When a long press is detected, I'm calling this function :
- (void)handleLongPressGesture:(UIGestureRecognizer*)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) return;
NSLog(#"long press");
CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
CLLocationCoordinate2D touchMapCoordinate =
[mapView convertPoint:touchPoint toCoordinateFromView:mapView];
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
[rdvAnnotation initWithCoordinate:touchMapCoordinate];
[mapView removeAnnotations:mapView.annotations];
[mapView addAnnotation:rdvAnnotation];
[rdvAnnotation release]; }
I cans see the NSLog in the console and the rdvAnnotation is initialized with the good coordinate.
I don't understand why I can't see my annotation on the map.
Here's my - (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation method:
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if ([annotation isKindOfClass:[RdvAnnotation class]])
{
static NSString* RdvAnnotationIdentifier = #"rdvAnnotationIdentifier";
MKPinAnnotationView* pinView = (MKPinAnnotationView *)
[mapView dequeueReusableAnnotationViewWithIdentifier:RdvAnnotationIdentifier];
if (!pinView)
{
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:RdvAnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorPurple;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
return customPinView;
}
else
{
pinView.annotation = annotation;
}
return pinView;
}
return nil;}
My viewDidLoad method:
- (void)viewDidLoad {
[super viewDidLoad];
mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[mapView setShowsUserLocation:TRUE];
[mapView setMapType:MKMapTypeStandard];
[mapView setDelegate:self];
CLLocationManager *locationManager=[[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
[locationManager startUpdatingLocation];
self.navigationItem.title = #"Rendez-vous" ;
}
I just noticed something that seems weird :
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
[rdvAnnotation initWithCoordinate:touchMapCoordinate];
You're calling init twice on the annotation object. You should just do it this way :
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] initWithCoordinate:touchMapCoordinate]];
EDIT :
If you have code in your init method that you don't want to lose, keep the init and change the value of the coordinate property :
RdvAnnotation *rdvAnnotation = [[RdvAnnotation alloc] init];
rdvAnnotation.coordinate = touchMapCoordinate;
In viewDidLoad you are creating a new map view object.
First, this new map view object is not being added as a subview to self.view so it exists in memory but is invisible.
Second, you probably already have a map view object placed in the view in Interface Builder so you don't need to create a new one.
So what is probably happening is that when you add the annotation, it is being added to the map view object in memory but not the one that is visible (the one that was created in IB).
Instead of creating a new map view in viewDidLoad, connect the mapView IBOutlet to the map view in Interface Builder.