change location to coordinates and also call didUpdateUserLocation method - iphone

This is my implementation file :
#import "mapViewController.h"
#interface mapViewController ()
#end
#implementation mapViewController
#synthesize mapView,source,dest,latdest,latsource,longdest,longsource;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
dest=#"delhi";
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CLGeocoder *geocoder1 = [[CLGeocoder alloc] init];
[geocoder1 geocodeAddressString:source
completionHandler:^(NSArray* placemarks, NSError* error)
{
for (CLPlacemark* aPlacemark in placemarks)
{
CLLocationCoordinate2D coordinate;
coordinate.latitude = aPlacemark.location.coordinate.latitude;
latsource=&coordinate.latitude;
coordinate.longitude = aPlacemark.location.coordinate.longitude;
longsource=&coordinate.longitude;
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:(coordinate)];
[annotation setTitle:source];
annotation.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:annotation];
}
}];
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region =MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = userLocation.coordinate;
point.title = #"Where am I?";
point.subtitle = #"I'm here!!!";
[self.mapView addAnnotation:point];
[self.view addSubview:self.mapView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This is my header file :
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface mapViewController : UIViewController <MKMapViewDelegate>
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property(strong,nonatomic) NSString *source,*dest;
#property(nonatomic) CLLocationDegrees *latsource,*longsource;
#property(nonatomic) CLLocationDegrees *latdest,*longdest;
#end
First i want to know why didUpdateUserLocation method is never called.I also want to know the code to add a destination whose coordinates are stored in latdest and longdest.Both of them will get their values from static variable "dest" which has the value "delhi" in it .My final aim is to trace a route on the map from source coordinates(latsource,longsource) to destination coordinates(latest,longdest).
I am new to ios development so i might have done some noob mistakes.

didUpdateUserLocation method won't be called if you not set mapView.delegate = self;
If you use a class, which has delegate methods, and you want to use them, everytime you should set its delegate = self
Don't use the same name as in delegates: mapView
in header:
#property (weak, nonatomic) IBOutlet MKMapView *myMapView;
be sure you connected the IBOutlet MKMapView *myMapView in IterfaceBuilder
in implementation file:
#synthesize myMapView;
in your - (void)viewDidLoad
myMapView.delegate = self;
you have to correct all self.mapView to myMapView
You made a really big mistake:
if you use IBOutlet you have to add on InterfaceBuilder , and connect it.
or you can create everything from code:
#property (weak, nonatomic) MKMapView *myMapView;
myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,320,480)];
then add the screen with
[self.view addSubview:myMapView];

Related

how do i use UISlider to change the MKMapView zoomIn and ZoomOut in iphone?

how do i use the UISlider to change the zoom value of a MKMapView.
i tried this code but in works not perfectly,
- (IBAction)slideAction:(id)sender
{
span.latitudeDelta = 125*(1-slideValue.value)+0.01;
span.longitudeDelta = 0.001;
region.span = span;
region.center=map.centerCoordinate;
[map setRegion:region animated:TRUE];
}
any suggestions? i think their is no default zoom controller for MKMap?
Note that your longitudeDelta needs to change or it probably won't zoom.
You might find this useful: https://github.com/calabash/calabash-ios-server/blob/master/calabash/Classes/MapKit/MKMapView%2BZoomLevel.m
(I copied most of it from http://troybrant.net/blog/2010/01/set-the-zoom-level-of-an-mkmapview/)
//
// ViewController.m
// MapKitRegion
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AddressBook/AddressBook.h>
#interface ViewController () <MKMapViewDelegate>
#property (strong, nonatomic) IBOutlet UITextView *txtAddress;
#property (strong, nonatomic) IBOutlet UIButton *btnGetMap;
#property (strong, nonatomic) IBOutlet UISegmentedControl *segType;
#property (strong, nonatomic) IBOutlet UISlider *slideZoom;
#property (strong, nonatomic) IBOutlet MKMapView *mapView;
#property CLLocationCoordinate2D coord;
- (IBAction)btnGetMapTouched:(id)sender;
- (IBAction)segTypeChanged:(id)sender;
- (IBAction)slideZoomChanged:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_mapView.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)btnGetMapTouched:(id)sender {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:self.txtAddress.text
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"Geocode failed with error: %#", error);
return;
}
if(placemarks && placemarks.count > 0) {
CLPlacemark *placemark = placemarks[0];
_coord = placemark.location.coordinate;
_mapView.centerCoordinate = _coord;
[self SetZoom];
}
}];
}
- (IBAction)segTypeChanged:(id)sender {
if (self.segType.selectedSegmentIndex == 0)
_mapView.mapType = MKMapTypeStandard;
else
_mapView.mapType = MKMapTypeSatellite;
}
- (IBAction)slideZoomChanged:(id)sender {
[self SetZoom];
}
- (void) SetZoom {
int meters = self.slideZoom.value * 30000;
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance (_coord, meters, meters);
[_mapView setRegion:region animated:NO];
}
#end

How to trigger a video when a user reaches a certain location?

This is my CoreLocationController.h objective c class
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
extern const CLLocationAccuracy kCLLocationAccuracyBest;
#protocol CoreLocationControllerDelegate
#required
- (BOOL)startRegionMonitoring;
- (void)locationUpdate:(CLLocation *)location; // Our location updates are sent here
- (void)locationError:(NSError *)error; // Any errors are sent here
#end
#interface CoreLocationController : NSObject <CLLocationManagerDelegate, MKMapViewDelegate> {
CLLocationManager *locMgr;
CLLocationCoordinate2D coordinate;
IBOutlet MKMapView *worldView;
IBOutlet UIActivityIndicatorView *activityIndicator;
id delegate;
}
#property (nonatomic, retain) CLLocationManager *locMgr;
#property (nonatomic, assign) id delegate;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
#end
and this is the CorelocationController.m
#import "CoreLocationController.h"
#implementation CoreLocationController
#synthesize locMgr, delegate, coordinate;
- (id)init {
self = [super init];
if(self != nil) {
self.locMgr = [[[CLLocationManager alloc] init] autorelease]; // Create new instance of locMgr
self.locMgr.delegate = self; // Set the delegate as self.
[locMgr setDistanceFilter:kCLDistanceFilterNone];
[locMgr setDesiredAccuracy:kCLLocationAccuracyBest];
[worldView setShowsUserLocation:YES];
}
return self;
}
- (BOOL)startRegionMonitoring {
if (![CLLocationManager regionMonitoringAvailable] || ![CLLocationManager regionMonitoringEnabled] )
return NO;
CLLocationCoordinate2D home;
home.latitude = +51.49410630;
home.longitude = -0.10251360;
CLRegion * region = [[CLRegion alloc] initCircularRegionWithCenter:home radius:10.0 identifier:#"home"];
if (locMgr == nil)
locMgr = ([[CLLocationManager alloc] init]);
[locMgr startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest];
[region release];
return YES;
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(#"Enteed location");
// [self leavingHomeNotify];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location entered" message:#"Region entered" delegate:NULL cancelButtonTitle:#"OK" otherButtonTitles:NULL];
[alert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:#protocol(CoreLocationControllerDelegate)]) { // Check if the class assigning itself as the delegate conforms to our protocol. If not, the message will go nowhere. Not good.
[self.delegate locationUpdate:newLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if([self.delegate conformsToProtocol:#protocol(CoreLocationControllerDelegate)]) { // Check if the class assigning itself as the delegate conforms to our protocol. If not, the message will go nowhere. Not good.
[self.delegate locationError:error];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Location failed" message:#"Location failed" delegate:NULL cancelButtonTitle:#"OK" otherButtonTitles:NULL];
[alert show];
}
- (void)dealloc {
[self.locMgr release];
[super dealloc];
}
#end
This is the CoreLocationDemoViewer.h
#import <UIKit/UIKit.h>
#import "CoreLocationController.h"
#import <MapKit/MapKit.h>
#interface CoreLocationDemoViewController : UIViewController <CoreLocationControllerDelegate, MKMapViewDelegate> {
CoreLocationController *CLController;
IBOutlet UILabel *locLabel;
MKMapView *worldView;
}
#property (nonatomic, retain) CoreLocationController *CLController;
#property (nonatomic, retain) IBOutlet UILabel *locLabel;
#property (nonatomic, retain) MKMapView *worldView;
#end
This is the CoreLocationDemoViewer.m
#import "CoreLocationDemoViewController.h"
#implementation CoreLocationDemoViewController
#synthesize CLController;
#synthesize locLabel;
#synthesize worldView;
- (void)viewDidLoad {
[super viewDidLoad];
self.worldView.mapType = MKMapTypeStandard; // also MKMapTypeSatellite or MKMapTypeHybrid
CLController = [[CoreLocationController alloc] init];
CLController.delegate = self;
[CLController.locMgr startUpdatingLocation];
worldView.zoomEnabled = YES;
worldView.scrollEnabled = YES;
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)u
{
CLLocationCoordinate2D loc = [u coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
- (void)locationUpdate:(CLLocation *)location {
locLabel.text = [location description];
// [mapView setCenterCoordinate:location.coordinate];
// [mapView setShowsUserLocation:YES];
CLLocationCoordinate2D coord = [location coordinate];
// Add it to the map view
// [worldView addAnnotation:mp];
// MKMapView retains its annotations, we can release
// [mp release];
// Zoom the region to this location
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 50, 50);
[worldView setRegion:region animated:YES];
// [locationManager stopUpdatingLocation];
}
- (void)locationError:(NSError *)error {
locLabel.text = [error description];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)viewDidUnload {
[super viewDidUnload];
self.worldView = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[CLController release];
[worldView release];
[super dealloc];
}
#end
Ok so this is what i want. Until now it shows a map with the user location
and it finds the exact location which is shown on a label.. correct if i am doing anything wrong..
What i want to do is trigger a video when a user reaches a certain location...
IAm approaching right?
I think if you are just having trouble getting the mapView to zoom correctly, use the MKCoordinate stuff from this post, How do I zoom an MKMapView.
I am working on a mapview as well that zooms to a decent level for viewing, and I am setting the lattitudeDelta and longitudeDelta for the map. Works good for me.
Perhaps something is wrong with setting the delegate? I usually specify the delegate in the .h file like this:
id <CoreLocationControllerDelegate> delegate;
and
#property (nonatomic, assign) id <CoreLocationControllerDelegate> delegate;
EDIT
Also, did you check that -mapView:didUpdateUserLocation: is being called?
I don't see you assigning the delegate for worldView (but you do for your other stuff). Try adding worldView.delegate = self; in your viewDidLoad.

"Program received signal "SIGABRT" when building a calculator

(I'm beginner.)
I'm practicing Navigation Controller. I try to implement a simple calculator.
I ran the code in simulator. After I pressed any button which was linked to "addFunction", "substractFunction", "multiplyFunction" or "divideFunction", It crashed.
The debugger marked the following code in main.m
int retVal = UIApplicationMain(argc, argv, nil, nil);
and said "Thread 1: Program received signal: "SIGABRT"."
Does anyone know how to cope with this situation? Thanks.
Here's the code:
ChangeAppView.h:
#import <UIKit/UIKit.h>
#class ChangeViewController;
#interface ChangeAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) UINavigationController *navigationController;
#end
ChangeAppDelegate.m:
#import "ChangeAppDelegate.h"
#import "ChangeViewController.h"
#implementation ChangeAppDelegate
#synthesize window;
#synthesize navigationController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
navigationController = [[UINavigationController alloc] init];
self.window.rootViewController = navigationController;
ChangeViewController *changeViewController = [[ChangeViewController alloc] initWithNibName:#"ChangeViewController" bundle:nil];
[navigationController pushViewController:changeViewController animated:YES];
[changeViewController release];
[self.window makeKeyAndVisible];
return YES;
}
…
- (void)dealloc
{
[navigationController release];
[window release];
[super dealloc];
}
#end
CalculatorViewController.h:
#import <UIKit/UIKit.h>
#interface CalculatorViewController : UIViewController
{
IBOutlet UITextField *numberField1;
IBOutlet UITextField *numberField2;
IBOutlet UILabel *resultLabel;
}
#property (nonatomic , retain) IBOutlet UITextField *numberField1;
#property (nonatomic , retain) IBOutlet UITextField *numberField2;
#property (nonatomic , retain) IBOutlet UILabel *resultLabel;
-(IBAction)addFunction:(id)sender;
-(IBAction)substractFunction:(id)sender;
-(IBAction)multiplyFunction:(id)sender;
-(IBAction)divideFunction:(id)sender;
-(IBAction)clear:(id)sender;
-(IBAction)backgroundTap:(id)sender;
#end
CalculatorViewController.m:
#import "CalculatorViewController.h"
#implementation CalculatorViewController
#synthesize numberField1;
#synthesize numberField2;
#synthesize resultLabel;
-(IBAction)addFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [NSString stringWithFormat:#"%2.f" , a+b];
}
-(IBAction)substractFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
NSString *result = [[NSString alloc] initWithFormat:#"%2.f" , a-b];
resultLabel.text = result;
[result release];
}
-(IBAction)multiplyFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.f" , a*b];
}
-(IBAction)divideFunction:(id)sender
{
float a = ([numberField1.text floatValue]);
float b = ([numberField2.text floatValue]);
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.3f" , a/b];
}
-(IBAction)clear:(id)sender
{
numberField1.text = #"";
numberField2.text = #"";
resultLabel.text = #"";
}
-(IBAction)backgroundTap:(id)sender
{
[numberField1 resignFirstResponder];
[numberField2 resignFirstResponder];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[numberField1 release];
[numberField2 release];
[resultLabel release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.title = #"Calculator";
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
From the exception above, it seems that your IBActions are not properly connected.
As dasdom mentioned, delete all your buttons, create new buttons and then add IBAction methods accordingly.
Also one more thing i recognized in your code, in the multiply and divide methods there is a memory leak.You have written
resultLabel.text = [[NSString alloc] initWithFormat:#"%2.f" , a*b];
it should be
resultLabel.text = [[[NSString alloc] initWithFormat:#"%2.f" , a*b]autorelease];
or
resultLabel.text = [NSString StringWithFormat:#"%2.f" , a*b];
and do a similar change in divide method also.
To what did you link your backgroundtap method?
It seems that you buttons aren't buttons. They seem to be view. Delete the buttons from you nib and put new buttons there and link them you our IBActions.

Problems Adding MKPolygon as an Overlay to an MKMapView

Ey there, so as the title says, I am having a tough time adding an MKPolygon as an overlay to an MKMapView. Here is the relevant code:
ParkingMapViewContoller.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ParkingMapViewController : UIViewController <MKMapViewDelegate> {
MKMapView *mapView;
}
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
-(void)loadAnnotations;
-(void)showCurrentLocationButtonTapped:(id)sender;
#end
ParkingMapViewController.m
//...
#import "ParkingRegionOverlay.h"
//...
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#",self.title);
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:100 target:self action:#selector(showCurrentLocationButtonTapped:)];
/*MKMapPoint points[3] = {{38.53607,-121.765793}, {38.537606,-121.768379}, {38.53487,-121.770578}};
MKPolygon *polygon = [MKPolygon polygonWithPoints:points count:3];*/
ParkingRegionOverlay *polygon = [[ParkingRegionOverlay alloc] initialize];
[mapView addOverlay:polygon];
[self loadAnnotations];
CLLocationCoordinate2D centerCoord = { UCD_LATITUDE, UCD_LONGITUDE };
[mapView setCenterCoordinate:centerCoord zoomLevel:13 animated:NO]; //from "MKMapView+ZoomLevel.h"
}
//...
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
NSLog(#"in viewForOverlay!");
if ([overlay isKindOfClass:[MKPolygon class]])
{
MKPolygonView* aView = [[[MKPolygonView alloc] initWithPolygon:(MKPolygon*)overlay] autorelease];
aView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2];
aView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
aView.lineWidth = 3;
return aView;
}
return nil;
}
//...
ParkingRegionOverlay.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface ParkingRegionOverlay : NSObject <MKOverlay> {
//CLLocationCoordinate2D origin;
MKPolygon *polygon;
//MKMapRect rect;
}
//#property (nonatomic) CLLocationCoordinate2D origin;
#property (nonatomic, retain) MKPolygon *polygon;
//#property (nonatomic) MKMapRect rect;
-(ParkingRegionOverlay*)initialize;
-(MKMapRect)boundingMapRect;
-(CLLocationCoordinate2D)coordinate;
#end
ParkingRegionOverlay.m
#import "ParkingRegionOverlay.h"
#implementation ParkingRegionOverlay
//#synthesize origin;
#synthesize polygon;
//#synthesize rect;
-(ParkingRegionOverlay*) initialize {
MKMapPoint points[3] = {{38.53607,-121.765793}, {38.537606,-121.768379}, {38.53487,-121.770578}};
polygon = [MKPolygon polygonWithPoints:points count:3];
polygon.title = #"Some Polygon";
return self;
}
- (MKMapRect)boundingMapRect{
MKMapRect bounds = MKMapRectMake(-121.770578,38.537606,-121.770578-(-121.765793),38.537606-38.53487);
return bounds;
}
- (CLLocationCoordinate2D)coordinate{
return CLLocationCoordinate2DMake((38.537606-38.53487)/2, (-121.770578-(-121.765793))/2);
}
#end
You see that NSLog I stuck in the viewForOverlay: method? Well that never shows up in the console, so that function is never called. Any idea of what's wrong? Many thanks!
The main issue is that the code is giving the map view latitude/longitude coordinates where it expects MKMapPoints. For an explanation of the difference, see "Understanding Map Geometry" in the Location Awareness Programming Guide. Use the MKMapPointForCoordinate function to convert from lat/long coordinates to an MKMapPoint.
The second issue is that in viewForOverlay, it is checking if overlay is of type MKPolygon. Your overlay class ParkingRegionOverlay contains an MKPolygon object inside it but is not itself of type MKPolygon.
To fix the main issue, you need to change the initialize and boundingMapRect methods:
-(id)init {
if (self = [super init]) {
MKMapPoint points[3];
CLLocationCoordinate2D c1 = {38.53607,-121.765793};
points[0] = MKMapPointForCoordinate(c1);
CLLocationCoordinate2D c2 = {38.537606,-121.768379};
points[1] = MKMapPointForCoordinate(c2);
CLLocationCoordinate2D c3 = {38.53487,-121.770578};
points[2] = MKMapPointForCoordinate(c3);
polygon = [MKPolygon polygonWithPoints:points count:3];
polygon.title = #"Some Polygon";
}
return self;
}
- (MKMapRect)boundingMapRect{
CLLocationCoordinate2D corner1 =
CLLocationCoordinate2DMake(38.537606, -121.770578);
MKMapPoint mp1 = MKMapPointForCoordinate(corner1);
CLLocationCoordinate2D corner2 =
CLLocationCoordinate2DMake(38.53487, -121.765793);
MKMapPoint mp2 = MKMapPointForCoordinate(corner2);
MKMapRect bounds =
MKMapRectMake(mp1.x, mp1.y, (mp2.x-mp1.x), (mp2.y-mp1.y));
return bounds;
}
Please notice by the way that I changed the method "initialize" to "init". Though it wasn't preventing the polygon from showing, the way you are overriding the initialization of ParkingRegionOverlay using a method called "initialize" and not calling [super init] does not follow convention. (Also remove "initialize" from the .h file.)
To fix the second issue, the viewForOverlay method should look like this:
- (MKOverlayView *)mapView:(MKMapView *)mapView
viewForOverlay:(id <MKOverlay>)overlay
{
NSLog(#"in viewForOverlay!");
if ([overlay isKindOfClass:[ParkingRegionOverlay class]])
//^^^^^^^^^^^^^^^^^^^^
{
//get the MKPolygon inside the ParkingRegionOverlay...
MKPolygon *proPolygon = ((ParkingRegionOverlay*)overlay).polygon;
MKPolygonView *aView = [[[MKPolygonView alloc]
initWithPolygon:proPolygon] autorelease];
//^^^^^^^^^^
aView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2];
aView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
aView.lineWidth = 3;
return aView;
}
return nil;
}
Finally, change the code in viewDidLoad:
ParkingRegionOverlay *polygon = [[ParkingRegionOverlay alloc] init];
[mapView addOverlay:polygon];
[polygon release]; //don't forget this
it seems to me that you forget to set your delegate
somthing like that
_mapView.delegate = self;
Have you set this?:
yourMap.delegate=self;
And what's your target? 3.x or 4.x?? I think MKPolygon is available from 4.0.
You can try to add the import clause to your prefix file like:
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#endif

How can I pass latitude and longitude values from UIViewController to MKMapView?

I have a detail view that includes three UIButtons, each of which pushes a different view on to the stack. One of the buttons is connected to a MKMapView. When that button is pushed I need to send the latitude and longitude variables from the detail view to the map view. I'm trying to add the string declaration in the IBAction:
- (IBAction)goToMapView {
MapViewController *mapController = [[MapViewController alloc] initWithNibName:#"MapViewController" bundle:nil];
mapController.mapAddress = self.address;
mapController.mapTitle = self.Title;
mapController.mapLat = self.lat;
mapController.mapLng = self.lng;
//Push the new view on the stack
[[self navigationController] pushViewController:mapController animated:YES];
[mapController release];
//mapController = nil;
}
And on my MapViewController.h file I have:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "DetailViewController.h"
#import "CourseAnnotation.h"
#class CourseAnnotation;
#interface MapViewController : UIViewController <MKMapViewDelegate>
{
IBOutlet MKMapView *mapView;
NSString *mapAddress;
NSString *mapTitle;
NSNumber *mapLat;
NSNumber *mapLng;
}
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property (nonatomic, retain) NSString *mapAddress;
#property (nonatomic, retain) NSString *mapTitle;
#property (nonatomic, retain) NSNumber *mapLat;
#property (nonatomic, retain) NSNumber *mapLng;
#end
And on the pertinent parts of the MapViewController.m file I have:
#synthesize mapView, mapAddress, mapTitle, mapLat, mapLng;
- (void)viewDidLoad
{
[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = mapLat; //40.105085;
region.center.longitude = mapLng; //-83.005237;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
CourseAnnotation *ann = [[CourseAnnotation alloc] init];
ann.title = mapTitle;
ann.subtitle = mapAddress;
ann.coordinate = region.center;
[mapView addAnnotation:ann];
}
But I get this when I try to build: 'error: incompatible types in assignment' for both lat and lng variables. So my questions are am I going about passing the variables from one view to another the right way? And does the MKMapView accept latitude and longitude as a string or a number?
Latitude and longitude in MapKit are stored as CLLocationDegrees types, which is defined as double. To convert your NSNumbers to doubles, use:
region.center.latitude = [mapLat doubleValue];
Or, perhaps better, declare your properties as CLLocationDegrees from the start.