I am making an app that will use the MKMapKit for the pins and annotations. I want to display more information besides some text, so I created a button in the callout so I could make that go to another view controller. At the moment, the button in the callout doesn't do anything, as there is no code to make it work. It would be great if someone could make the code for the button to go to a different view controller!
The header file
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#define METERS_PER_MILE 1609.344
#interface MSKSecondViewController :UIViewController<MKMapViewDelegate>
{
IBOutlet MKMapView *stillwellMapView;
int difficultyOfTrailOverlay;
}
#property (nonatomic, assign) CLLocationCoordinate2D mainEntranceToStillwellCoordinate;
#end
Here is the implementation file
#import "MSKSecondViewController.h"
#interface MSKSecondViewController ()
#end
#implementation MSKSecondViewController
#synthesize mainEntranceToStillwellCoordinate;
- (void)viewDidLoad
{
[super viewDidLoad];
stillwellMapView.delegate=self;
// Do any additional setup after loading the view, typically from a nib.
[self mainEntrancetoStillwellCoordinate];
[self bambooForestCoordinate];
}
- (void)mainEntrancetoStillwellCoordinate
{
MKPointAnnotation * main = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D mainLocation;
mainLocation.latitude = 40.831685;
mainLocation.longitude = -73.477453;
[main setCoordinate:mainLocation];
[main setTitle:#"Entrance"];
[main setSubtitle:#"Main"];
[stillwellMapView addAnnotation:main];
}
- (void)bambooForestCoordinate
{
MKPointAnnotation * bambooForest = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D bambooForestLocation;
bambooForestLocation.latitude = 40.829118;
bambooForestLocation.longitude = -73.466443;
[bambooForest setCoordinate:bambooForestLocation];
[bambooForest setTitle:#"Bamboo Forest"];
[bambooForest setSubtitle:#"Exit to Woodbury"];
[stillwellMapView addAnnotation:bambooForest];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation
(id<MKAnnotation>)annotation
{
MKPinAnnotationView * annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:nil];
UIButton *moreInformationButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[moreInformationButton addTarget:self action:#selector(moreInformationButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = moreInformationButton;
moreInformationButton.frame = CGRectMake(0, 0, 23, 23);
moreInformationButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
moreInformationButton.contentHorizontalAlignment =
UIControlContentHorizontalAlignmentCenter;
annView.pinColor =MKPinAnnotationColorGreen;
annView.animatesDrop = true;
annView.canShowCallout = TRUE;
return annView;
}
I'm not sure if this is what I need to add, and what needs to go inside here
-(void) moreInformationButtonPressed:(UIButton *)sender
{
}
Write below kind of code:
-(void) moreInformationButtonPressed:(UIButton *)sender
{
OtherViewController *controller = [[OtherViewController alloc]initWithNibName:#"OtherViewController" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
first you should make a tag that you can know which annotation is clicked
moreInformationButton.tag = someIndex;
then do the action you want
-(void) moreInformationButtonPressed:(UIButton *)sender
{
int index = sender.tag;
YourController *yc =[[[YourController alloc] initWithIndex:index] autorelease];
[self.navigationController pushViewController:scanView animated:YES];
}
Related
I have inherited some old iOS code and have attempted to integrate it into a new iOS 6 application. I have implemented most of the code and so far everything has worked. I'm now working on the last bit of that old code. I'm implementing a set of views to show a rss for a news section of my app. I've implemented the categories view, which upon selecting an item would display the individual items within that category. However nothing gets displayed. I've made all the modifications that I'm aware of that I needed to do, however I'm no expert at iOS development and am in need of some guidance. Below is a snapshot of the simulator as it's attempting to display the view, and below that is a copy of my .h and .m files. I don't know what is preventing anything in the table from showing up. And preemptive thanks to any help!
here's the snapshot of the simulator
Here is a snapshot of the storyboard showing the linking to the Table View
Here's the .h file
#import <UIKit/UIKit.h>
#import "BlogRssParser.h"
#class BlogRssParser;
#class BlogRssParserDelegate;
#class BlogRss;
#class XMLCategory;
#interface NewsViewController : UIViewController <UITableViewDataSource,UITableViewDelegate, BlogRssParserDelegate> {
BlogRssParser * _rssParser;
XMLCategory * _currItem;
}
#property (nonatomic, retain) BlogRssParser * rssParser;
#property (readwrite, retain) XMLCategory * currItem;
#property (nonatomic, retain) IBOutlet UITableView *itemTableView;
#end
Here is my .m file
#import "NewsViewController.h"
#import "NewsDetailsViewController.h"
#import "BlogRssParser.h"
#import "BlogRss.h"
#import "XMLCategory.h"
#define kLabelTag 1;
#interface NewsViewController ()
#end
#implementation NewsViewController
#synthesize rssParser = _rssParser;
#synthesize currItem = _currItem;
- (void)navBarInit {
UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:#selector(reloadRss)];
[self.navigationItem setRightBarButtonItem:refreshBarButton animated:YES];
}
- (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.
self.itemTableView.delegate = self;
self.itemTableView.dataSource = self;
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self navBarInit];
[self.itemTableView reloadData];
self.itemTableView.userInteractionEnabled = NO;
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_rssParser = [[BlogRssParser alloc]init];
_rssParser.delegate = self;
[[self rssParser]startProcess:[_currItem categoryId]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)reloadRss{
[[self rssParser]startProcess:[_currItem categoryId]];
[[self itemTableView]reloadData];
}
- (void)processCompleted{
[[self itemTableView]reloadData];
// _tableView.userInteractionEnabled = YES;
[[self itemTableView]setUserInteractionEnabled:YES];
}
-(void)processHasErrors{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"My Title" message:#"Unable to retrieve the news. Please check if you are connected to the internet."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
const CGFloat LABEL_TITLE_HEIGHT = 70.0;
const CGFloat LABEL_WIDTH = 210.0;
NSString * mediaUrl = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]mediaUrl];
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
UIImage * imageFromImageData;
if (imageData == nil) {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.urlForImage.image.png"]];
}
imageFromImageData = [[UIImage alloc] initWithData:imageData];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * _topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
imageFromImageData.size.width + 10.0,
0.0,
LABEL_WIDTH,
LABEL_TITLE_HEIGHT)];
_topLabel.tag = kLabelTag;
_topLabel.opaque = NO;
_topLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
_topLabel.backgroundColor = [UIColor clearColor];
_topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
_topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
_topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
_topLabel.numberOfLines = 0;
[cell.contentView addSubview:_topLabel];
}
cell.imageView.image = imageFromImageData;
UILabel * topLabel = (UILabel *)[cell.contentView viewWithTag:1];
topLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NewsDetailsViewController *tlc = [[DetailsViewController alloc]init];
tlc.currentItem = [[[self rssParser]rssItems]objectAtIndex:indexPath.row];
tlc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:tlc animated:YES completion:nil];
}
#end
I could not get a conclusion about the problem you are facing.
But here are few things you should check.
Because i cannot see even an empty table view in your screenshot
Do you have the TableView on the Nib file ?
It is mapped from The Nib file to the IBOutlet itemTableView ?
Add at least one table view cell (Drag and drop one prototype cell)..
like this
Then select that cell and give some name in "Reuse Identifier" with this identifier allow datasource..
First thing I would do is make sure that [[[self rssParser] rssItems] count] is actually returning > 0. Also, is this a copy&paste of your .m file? viewDidLoad is missing the closing brace, but Xcode would catch that.
I want the button in the callout to go to another view controller to display extra information, and then be able to come back to the map view. the map is inside of a tabbed view controller. At the moment, if you click on the button in the callout, the app crashes and gives you a thread error. Not sure on what to do at the moment.
this is the header file:
#import UIKit/UIKit.h>
#import MapKit/MapKit.h>
#define METERS_PER_MILE 1609.344
#interface MSKSecondViewController :UIViewController<MKMapViewDelegate>
{
IBOutlet MKMapView *stillwellMapView;
}
#property (nonatomic, assign) CLLocationCoordinate2D mainEntranceToStillwellCoordinate;
#end
and this is the implementation file:
#interface MSKSecondViewController ()
#end
#implementation MSKSecondViewController
#synthesize mainEntranceToStillwellCoordinate;
- (void)viewDidLoad
{
[super viewDidLoad];
stillwellMapView.delegate=self;
// Do any additional setup after loading the view, typically from a nib.
[self mainEntrancetoStillwellCoordinate];
[self bambooForestCoordinate];
}
- (void)mainEntrancetoStillwellCoordinate
{
MKPointAnnotation * main = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D mainLocation;
mainLocation.latitude = 40.831685;
mainLocation.longitude = -73.477453;
[main setCoordinate:mainLocation];
[main setTitle:#"Entrance"];
[main setSubtitle:#"Main"];
[stillwellMapView addAnnotation:main];
}
- (void)bambooForestCoordinate
{
MKPointAnnotation * bambooForest = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D bambooForestLocation;
bambooForestLocation.latitude = 40.829118;
bambooForestLocation.longitude = -73.466443;
[bambooForest setCoordinate:bambooForestLocation];
[bambooForest setTitle:#"Bamboo Forest"];
[bambooForest setSubtitle:#"Exit to Woodbury"];
[stillwellMapView addAnnotation:bambooForest];
}
- (void)viewDidUnload
{
stillwellMapView = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:
(id<MKAnnotation>)annotation
{
MKPinAnnotationView * annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
UIButton *entranceButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[entranceButton addTarget:self action:#selector(entranceButtonPressed:)
forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = entranceButton;
entranceButton = [UIButton buttonWithType:UIButtonTypeCustom];
entranceButton.frame = CGRectMake(0, 0, 23, 23);
entranceButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
entranceButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)viewWillAppear:(BOOL)animated
{
//the coordinates in which the map shows once loaded
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 40.831922;
zoomLocation.longitude= -73.476353;
//the amount of area shown by the map when it loads
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation,
0.15*METERS_PER_MILE, 0.15*METERS_PER_MILE);
MKCoordinateRegion adjustedRegion = [stillwellMapView regionThatFits:viewRegion];
[stillwellMapView setRegion:adjustedRegion animated:YES];
}
#end
Add the event which you have registered on Touch Up Inside with entranceButton.
-(void) entranceButtonPressed:(UIButton *)sender
{
//Write the controller push code here
}
Also, in the code you have reinitialize the entranceButton once it is assigned to rightCalloutAccessoryView.
In the mapView:viewForAnnotation: delegate method
-(MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation
// add the following line
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
and then implement the code to navigate to other view controller in the following delegate method
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
Make sure view controller is embedded inside navigation controller
Is there something that I need to remember when using the windows-based template? Because I'm unclear as to why the tabs are showing up but nothing in the views are showing up.
Could you help? Because I've been searching through previous questions for a few hours now and I still haven't found anything to clear this up.
AnotherMadeUpAppDelegate.h
#import <UIKit/UIKit.h>
#import "AnotherMadeUpViewController.h"
#interface AnotherMadeUpAppDelegate : NSObject <UIApplicationDelegate> {
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#end
AnotherMadeUpAppDelegate.m
#import "AnotherMadeUpAppDelegate.h"
#implementation AnotherMadeUpAppDelegate
#synthesize window=_window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIViewController *vc1 = [[UIViewController alloc] init];
UIViewController *vc2 = [[UIViewController alloc] init];
AnotherMadeUpViewController *vc3 = [[AnotherMadeUpViewController alloc] init];
UITabBarController *tbc = [[UITabBarController alloc] init];
tbc.viewControllers = [NSArray arrayWithObjects:vc1, vc2, vc3, nil];
[vc1 release];
[vc2 release];
[vc3 release];
[self.window addSubview:tbc.view];
[self.window makeKeyAndVisible];
return YES;
}
...
#end
AnotherMadeUpViewController.h
#import <UIKit/UIKit.h>
#interface AnotherMadeUpViewController : UIViewController<UIScrollViewDelegate>
{
IBOutlet UIPageControl *pageControl;
IBOutlet UIScrollView *scroller;
IBOutlet UILabel *label;
}
#property (nonatomic,retain)IBOutlet UIPageControl *pageControl;
#property (nonatomic,retain)IBOutlet UIScrollView *scroller;
#property (nonatomic,retain)IBOutlet UILabel *label;
-(IBAction)clickPageControl:(id)sender;
#end
AnotherMadeUpViewController.m
#import "AnotherMadeUpViewController.h"
#implementation AnotherMadeUpViewController
#synthesize pageControl,scroller,label;
-(IBAction)clickPageControl:(id)sender
{
int page=pageControl.currentPage;
CGRect frame=scroller.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scroller scrollRectToVisible:frame animated:YES];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x/scrollView.frame.size.width;
pageControl.currentPage=page;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
[label release];
}
- (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
{
[super viewDidLoad];
scroller.pagingEnabled=YES;
CGFloat labelOriginX = label.frame.origin.x;
CGFloat labelOriginY = label.frame.origin.y;
CGFloat scrollWidth = 0;
int pageNumber = 0;
for (int i=0; i<9; i++)
{
CGRect rect = label.frame;
rect.size.height = label.frame.size.height;
rect.size.width = label.frame.size.width;
rect.origin.x = labelOriginX + scrollWidth;
rect.origin.y = labelOriginY;
label.frame = rect;
label.text = [NSString stringWithFormat:#"%d", pageNumber];
label.textColor = [UIColor redColor];
[scroller addSubview:label];
pageNumber++;
scrollWidth += scroller.frame.size.width;
}
scroller.delegate=self;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
pageControl.numberOfPages=9;
pageControl.currentPage=0;
scroller.contentSize=CGSizeMake(pageControl.numberOfPages*self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:scroller];
}
- (void)viewDidUnload
{
[super viewDidUnload];
[label release];
self.label = nil;
// 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
Dissecting your viewDidLoad –
scroller = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];
You seem to be creating a new scroll view instance here but you have declared it as an outlet. If you don't have an outlet then remove the IBOutlet tag for scroller. If you do have one and want to use it then remove the above line. A shorter way of doing it would be,
scroller = [[UIScrollView alloc] initWithFrame:self.view.bounds];
Another thing is that you are creating 10 labels but assigning no frame. To show one of them each in different page,
int pageNumber = 0;
for (int i = 0; i < 10; i++)
{
UILabel *label = [[UILabel alloc] init];
[label sizeToFit];
label.center = CGPointMake (((2 * i + 1) * self.view.frame.size.width) / 2, self.view.frame.size.height / 2);
label.text = [NSString stringWithFormat:#"%d", pageNumber];
[scroller addSubview:label];
[label release];
pageNumber++;
}
and later set the contentSize to show 10 pages,
scroller.contentSize = CGSizeMake(10 * self.view.frame.size.width, self.view.frame.size.height);
The problem is with this line
AnotherMadeUpViewController *vc3 = [[AnotherMadeUpViewController alloc] init];
You need to change it to
AnotherMadeUpViewController *vc3 = [[AnotherMadeUpViewController alloc] initWithNibName:#"AnotherMadeUpViewController" bundle:nil];
Then your .xib will get loaded and your outlets will be connected.
And don't forget to connect your outlets to File's owner in IB.
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
I have annotations in a MKMapView with Callouts. In this Callouts there's a "Right-Arrow" Button. When clicking on it, I want to open a Detail View, an extra UIViewController with its own nib file etc. I use following code:
In my MapViewController:
- (void)showDetails:(id)sender {
// the detail view does not want a toolbar so hide it
[self.navigationController setToolbarHidden:YES animated:NO];
NSLog(#"pressed!");
[self.navigationController pushViewController:self.detailViewController animated:YES];
NSLog(#"pressed --- 2!");
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(Annotation *) annotation {
if(annotation == map.userLocation) return nil;
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorRed;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView = rightButton;
UIImageView *memorialIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"googlemaps_pin.png"]];
customPinView.leftCalloutAccessoryView = memorialIcon;
[memorialIcon release];
return customPinView;
}
The button works, because when I give a NSLog inside the showDetais method, it's printed to the console. The problem is, that NOTHING happens. When clicking the button, it's like there isn't any button. There's no debug error or exception, just nothing.
the MapView header looks something like this:
#interface MapViewController : UIViewController <MKMapViewDelegate> {
MKMapView *map;
NSMutableDictionary *dictionary;
EntryDetailController *detailViewController;
}
#property (nonatomic,retain) IBOutlet MKMapView *map;
#property (nonatomic,retain) IBOutlet EntryDetailController *detailViewController;
Maybe someone of you can help me :)
Thanks!
Check if you have navigation controller for your viewController, if it is just a viewController then it cannot push a viewController because it does not have navigation controller in it.
I've had the same problem in the past and so I just used a different code to switch views:
-(IBAction)showDetails:(id)sender
{
NSLog(#"button clicked");
MapViewController *thisMap = (MapViewController *)[[UIApplication sharedApplication] delegate];
detailViewController *detailView = [[detailViewController alloc]initWithNibName:#"detailViewController" bundle:nil];
[thisMap switchViews:self.view toView:dvc.view];
}
It's a pretty basic view switching method and it works fine for me.
Isn't detailViewController uninitialized? You don't show all your code but I believe you might have things a bit jumbled up preparing the view and pushing it.
Why are you declaring the detailViewController as an IBOUTlet?
Also, I think you might want/intend to do this on your detailViewController not in this controller:
[self.navigationController setToolbarHidden:YES animated:NO];
You don't show all your code. But i guess, you just forget to initialise self.detailViewController.
try to add this in your viewDidLoad method:
self.detailViewController = [[[DetailViewController alloc]init]autorelease];