The searchBarBookmarkButtonClicked method isn't firing when I tap on the search bar. I have already added the self.searchBar.deleagate = self; and in my .h file I added the <UISearchBarDelegate>.
.h file:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController <UISearchBarDelegate,MKMapViewDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet MKMapView *myMap;
#end
.m file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.searchBar.delegate = self;
self.myMap.delegate = self;
}
- (void)searchBarBookmarkButtonClicked:(UISearchBar * )searchBar{
NSLog(#"working");
[self.searchBar resignFirstResponder];
NSLog(#"working");
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:self.searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
MKCoordinateRegion region;
CLLocationCoordinate2D newLocation = [placemark.location coordinate];
region.center = [(CLCircularRegion *)placemark.region center];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:newLocation];
[annotation setTitle:self.searchBar.text];
[self.myMap addAnnotation:annotation];
MKMapRect mr = [self.myMap visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
mr.origin.x = pt.x - mr.size.width * 0.5;
mr.origin.y = pt.y -mr.size.width * 0.25;
[self.myMap setVisibleMapRect:mr animated:YES];
}];
}
#end
Make sure you have
All delegate being set properly, this can be done either in code or
in storyboard.
Make use of correct delegate method to capture the
event.
If you think
- (void)searchBarBookmarkButtonClicked:(UISearchBar * )searchBar
then try using the other method which is more straight forward to trigger search
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
Try this UISearchBar delegate method:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
Thank you #Rahul! Turns out I was using the wrong method!
.h:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface ViewController : UIViewController <UISearchBarDelegate,MKMapViewDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet MKMapView *myMap;
#end
.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.searchBar.delegate = self;
self.myMap.delegate = self;
}
- (void)searchBarBookmarkButtonClicked:(UISearchBar * )searchBar{
[self.searchBar resignFirstResponder];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:self.searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
MKCoordinateRegion region;
CLLocationCoordinate2D newLocation = [placemark.location coordinate];
region.center = [(CLCircularRegion *)placemark.region center];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:newLocation];
[annotation setTitle:self.searchBar.text];
[self.myMap addAnnotation:annotation];
MKMapRect mr = [self.myMap visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
mr.origin.x = pt.x - mr.size.width * 0.5;
mr.origin.y = pt.y -mr.size.width * 0.25;
[self.myMap setVisibleMapRect:mr animated:YES];
}];
}
#end
Related
I am trying to display some icons on a MKMapView. I have achieved that by using this code:
MapPoint *placeObject = [[MapPoint alloc] initWithName:place.name
address:place.address
coordinate:place.location.coordinate
image:place.customMapPinImage
icon:place.icon
bookmark:place.bookmark
contents_ID:place.contents_ID
contents_lang_MAIN_ID:place.contents_lang_MAIN_ID
contents_lang_ID_ML:place.contents_lang_ID_ML];
[mapView addAnnotation:placeObject];
The problem is that, without changing anything in the code, the size of the icons changed and I don't know why. How can I adjust the size of the icons?
You need to write class annotations
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface Annotation : NSObject <MKAnnotation>
#property (nonatomic) CLLocationCoordinate2D coordinate;
#property (strong, nonatomic) NSString *myTitle;
+ (Annotation *)initAnnotation:(CLLocationCoordinate2D)coordinate title:(NSString *)title;
#end
Implementation
#import "Annotation.h"
#implementation Annotation
+ (Annotation *)initAnnotation:(CLLocationCoordinate2D)coordinate title:(NSString *)title
{
return [[Annotation alloc] initWithAnnotation:coordinate title:title];
}
- (instancetype)initWithAnnotation:(CLLocationCoordinate2D)coordinate title:(NSString *)title
{
self = [super init];
self.coordinate = coordinate;
self.myTitle = title;
return self;
}
#end
ViewController
#import "ViewController.h"
#import <MapKit/MapKit.h>
#import "Annotation.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//set coordinates
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(51.50851, -0.02172);
//add annotation
Annotation *annotation = [Annotation initAnnotation:coordinate title:#"Annotation"];
[self.mapView addAnnotation:annotation];
[self.mapView showAnnotations:#[annotation] animated:YES];
// add circle with radius
MKCircle *circle = [MKCircle circleWithCenterCoordinate:annotation.coordinate radius:10000];
[self.mapView addOverlay:circle];
//add region by coordinates
MKCoordinateRegion region;
region.center.latitude = 51.50851;
region.center.longitude = -0.02172;
// level zoom
region.span.latitudeDelta = 1;
region.span.longitudeDelta = 1;
region = [self.mapView regionThatFits:region];
[self.mapView setRegion:region animated:YES];
}
Do not forget to set the controller as a map delegate, and implement the circle mapping method
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>) overlay{
MKCircleRenderer *circleView = [[MKCircleRenderer alloc] initWithOverlay:overlay];
circleView.fillColor = [[UIColor greenColor] colorWithAlphaComponent:0.4];
return circleView;
}[![enter image description here][1]][1]
Pin appears, and you can adjust its size
https://prntscr.com/lvfjwi
I am trying to change the standard pin to my own image but I keep failing after several attempts.
I have tried different codes and guides that I have found here in this forum but none of them seems to work. I belive I am pasting the code in to my project wrongly. Any ideas how to replace the regular pin with my own image?
//.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MapPin : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
- (id)initWithLocation:(CLLocationCoordinate2D)coord;
#end
//.m
#import <Foundation/Foundation.h>
#import "MapPin.h"
#implementation MapPin
#synthesize coordinate,title,subtitle;
- (id)initWithLocation:(CLLocationCoordinate2D)coord{
self = [super init];
if (self) {
coordinate = coord;
}
return self;
}
#end
//Viewcontroller.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface FirstViewController : UIViewController <UIAlertViewDelegate, UIWebViewDelegate> {
MKMapView *mapview;
}
- (IBAction)information;
#property (strong, nonatomic) IBOutlet UIScrollView *ScrollView;
#property (strong, nonatomic) IBOutlet UIImageView *image;
#property (retain, nonatomic) IBOutlet MKMapView *mapview;
- (IBAction)showMenu;
- (IBAction)setMap:(id)sender;
- (IBAction)GetLocation:(id)sender;
#end
//Viewcontroller.m
#import "FirstViewController.h"
#import "MapPin.h"
#implementation FirstViewController
#synthesize ScrollView, image;
#synthesize mapview;
- (void)viewDidLoad{
MKCoordinateRegion region = { {0.0, 0.0}, {0.0,0.0}};
region.center.latitude = 55.709900;
region.center.longitude = 13.201207;
region.span.longitudeDelta = 0.032f;
region.span.latitudeDelta = 0.032f;
[mapview setRegion:region animated:YES];
MapPin *ann = [[MapPin alloc] init];
ann.title = #"test Town";
ann.subtitle = #"test Nation";
ann.coordinate = region.center;
ann.coordinate = region.center;
[mapview addAnnotation:ann];
MKCoordinateRegion region2 = { {0.0, 0.0}, {0.0,0.0}};
region2.center.latitude = 55.703904;
region2.center.longitude = 13.201207;
region2.span.longitudeDelta = 0.032f;
region2.span.latitudeDelta = 0.032f;
[mapview setRegion:region2 animated:YES];
MapPin *ann2 = [[MapPin alloc] init];
ann2.title = #"test Town";
ann2.subtitle = #"test Nation";
ann2.coordinate = region2.center;
ann2.coordinate = region2.center;
[mapview addAnnotation:ann2];
ScrollView.scrollEnabled = YES;
[ScrollView setContentSize:CGSizeMake(320, 515)];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor= MKPinAnnotationColorGreen;
pinView.enabled = YES;
pinView.canShowCallout = YES;
pinView.image=[UIImage imageNamed:#"test.png"]; //here I am giving the image
return pinView;
}
See my other answer for working implementation.
Setting an IBOutlet delegate:
Since you're using an IBOutlet for your MKMapView you should control-drag from your MKMapView in your storyboard/xib file to the ViewController/"File's Owner" and select "delegate" from the popup.
Here a SO answer that covers creating custom pins: Custom pins
Also,
pinView.image=[UIImage imageNamed:#"test.png"];
should be
pinView.image=[UIImage imageNamed:#"test"];
Reference: Image from imageNamed:
The following worked for me:
Make sure MapKit.framework has been added to your project.
Make sure test.png is in your project (preferably in Images.xcassets)
Control-drag from your mapView in your storyboard to the ViewController and connect "delegate".
Then...
#import "MapPin.h"
#import <MapKit/MapKit.h>
#interface ViewController () <MKMapViewDelegate>
#property (weak, nonatomic) IBOutlet MKMapView *mapview;
#end
#implementation ViewController
- (void)viewDidLoad
{
MKCoordinateRegion region = { {0.0, 0.0}, {0.0,0.0}};
region.center.latitude = 55.709900;
region.center.longitude = 13.201207;
region.span.longitudeDelta = 0.032f;
region.span.latitudeDelta = 0.032f;
[self.mapview setRegion:region animated:YES];
MapPin *ann = [[MapPin alloc] init];
ann.title = #"test Town";
ann.subtitle = #"test Nation";
ann.coordinate = region.center;
ann.coordinate = region.center;
[self.mapview addAnnotation:ann];
MKCoordinateRegion region2 = { {0.0, 0.0}, {0.0,0.0}};
region2.center.latitude = 55.703904;
region2.center.longitude = 13.201207;
region2.span.longitudeDelta = 0.032f;
region2.span.latitudeDelta = 0.032f;
[self.mapview setRegion:region2 animated:YES];
MapPin *ann2 = [[MapPin alloc] init];
ann2.title = #"test Town";
ann2.subtitle = #"test Nation";
ann2.coordinate = region2.center;
ann2.coordinate = region2.center;
[self.mapview addAnnotation:ann2];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if(annotationView) {
return annotationView;
} else {
MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:AnnotationIdentifier];
annotationView.image = [UIImage imageNamed:#"test"];
return annotationView;
}
}
#end
So I have followed the guidelines above, added the line of code and step3. Control-drag from your mapView in your storyboard to the ViewController and connect "delegate". which I named "pin".
But my image wont appear...I'll paste the new code again..there must be something wrong in it.
//Viewcontroller.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface FirstViewController : UIViewController <UIAlertViewDelegate, UIWebViewDelegate, MKMapViewDelegate> {
MKMapView *mapview;
}
- (IBAction)information;
#property (strong, nonatomic) IBOutlet UIScrollView *ScrollView;
#property (strong, nonatomic) IBOutlet UIImageView *image;
#property (retain, nonatomic) IBOutlet MKMapView *mapview;
#property (strong, nonatomic) IBOutlet MKMapView *pin;
- (IBAction)showMenu;
- (IBAction)setMap:(id)sender;
- (IBAction)GetLocation:(id)sender;
#end
//Viewcontroller.m
#import "FirstViewController.h"
#import "MapPin.h"
#implementation FirstViewController
#synthesize ScrollView, image;
#synthesize mapview;
#synthesize pin;
- (void)viewDidLoad{
MKCoordinateRegion region = { {0.0, 0.0}, {0.0,0.0}};
region.center.latitude = 55.709900;
region.center.longitude = 13.201207;
region.span.longitudeDelta = 0.032f;
region.span.latitudeDelta = 0.032f;
[self.mapview setRegion:region animated:YES];
MapPin *ann = [[MapPin alloc] init];
ann.title = #"test Town";
ann.subtitle = #"test Nation";
ann.coordinate = region.center;
ann.coordinate = region.center;
[self.mapview addAnnotation:ann];
MKCoordinateRegion region2 = { {0.0, 0.0}, {0.0,0.0}};
region2.center.latitude = 55.703904;
region2.center.longitude = 13.201207;
region2.span.longitudeDelta = 0.032f;
region2.span.latitudeDelta = 0.032f;
[self.mapview setRegion:region2 animated:YES];
MapPin *ann2 = [[MapPin alloc] init];
ann2.title = #"test Town";
ann2.subtitle = #"test Nation";
ann2.coordinate = region2.center;
ann2.coordinate = region2.center;
[self.mapview addAnnotation:ann2];
ScrollView.scrollEnabled = YES;
[ScrollView setContentSize:CGSizeMake(320, 515)];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if(annotationView) {
return annotationView;
} else {
MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:AnnotationIdentifier];
annotationView.image = [UIImage imageNamed:#"test"];
return annotationView;
}
}
#end
I have created 4 type of annotation group. In the map UI, I also added a tab bar on the bottom as my button.
My tab bar is used to filter out the annotation in MapKit.
For example... I have 4 group of annotation and 4 tab bar item.
When I clicked tab bar item 1, it show only 1 group of annotation in MapKit, other group of annotation will hide/remove in MapKit but I failed to achieve this kind of work.
My code:
in MapViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#interface MapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate , UITabBarDelegate>{
IBOutlet UITabBar *tabBar;
}
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
#property (weak, nonatomic) IBOutlet MKMapView *mapView;
#property (strong, nonatomic) CLLocationManager *locationManager;
#end
my mapViewController.m:
#import "MapViewController.h"
#import "SWRevealViewController.h"
#import "Annotation.h"
#interface MapViewController ()<CLLocationManagerDelegate>
#end
//set desitination of map
#define PENANG_LATI 5.419501;
#define PENANG_LONG 100.323264;
//shop
#define SHOP_LATI 5.419501;
#define SHOP_LONG 100.323264;
//cafe
#define CAFE_LATI 5.419917;
#define CAFE_LONG 100.322969;
//food
#define FOOD_LATI 5.419746;
#define FOOD_LONG 100.322610;
//mural
#define MURAL_LATI 5.419786;
#define MURAL_LONG 100.322510;
#define THE_SPAN 0.005f;
#implementation MapViewController
#synthesize mapView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//tabBar
tabBar.delegate = self;
MKCoordinateRegion myRegion;
//Center
CLLocationCoordinate2D center;
center.latitude = PENANG_LATI;
center.longitude = PENANG_LONG;
//SPAN
MKCoordinateSpan span;
span.latitudeDelta = THE_SPAN;
span.longitudeDelta = THE_SPAN;
myRegion.center = center;
myRegion.span = span;
//set map
[mapView setRegion:myRegion animated:YES];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
/*
//create coordinate
CLLocationCoordinate2D penangLocation;
penangLocation.latitude = PENANG_LATI;
penangLocation.longitude = PENANG_LONG;
Annotation * myAnnotation = [Annotation alloc];
myAnnotation.coordinate = penangLocation;
myAnnotation.title = #"THE ONE ACADEMY PENANG";
myAnnotation.subtitle = #"HELLO!! I STUDY HERE";
[self.mapView addAnnotation:myAnnotation];
*/
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
//my group of annotation location
NSMutableArray * myShop = [[NSMutableArray alloc] init];
NSMutableArray * myCafe = [[NSMutableArray alloc] init];
NSMutableArray * myFood = [[NSMutableArray alloc] init];
NSMutableArray * myMural = [[NSMutableArray alloc] init];
CLLocationCoordinate2D penangLocation;
Annotation * myShopAnnotation;
Annotation * myCafeAnnotation;
Annotation * myFoodAnnotation;
Annotation * myMuralAnnotation;
//shop location
myShopAnnotation = [[Annotation alloc] init];
penangLocation.latitude = SHOP_LATI;
penangLocation.longitude = SHOP_LONG;
myShopAnnotation.coordinate = penangLocation;
myShopAnnotation.title = #"Shop";
myShopAnnotation.subtitle = #"I study here";
[myShop addObject:myShopAnnotation];
//cafe location
myCafeAnnotation = [[Annotation alloc] init];
penangLocation.latitude = CAFE_LATI;
penangLocation.longitude = CAFE_LONG;
myCafeAnnotation.coordinate = penangLocation;
myCafeAnnotation.title = #"Cafe";
myCafeAnnotation.subtitle = #"I paid here";
[myCafe addObject:myCafeAnnotation];
//food location
myFoodAnnotation = [[Annotation alloc] init];
penangLocation.latitude = FOOD_LATI;
penangLocation.longitude = FOOD_LONG;
myFoodAnnotation.coordinate = penangLocation;
myFoodAnnotation.title = #"Food";
myFoodAnnotation.subtitle = #"I walk here";
[myFood addObject:myFoodAnnotation];
//Mural location
myMuralAnnotation = [[Annotation alloc] init];
penangLocation.latitude = MURAL_LATI;
penangLocation.longitude = MURAL_LONG;
myMuralAnnotation.coordinate = penangLocation;
myMuralAnnotation.title = #"Mural";
myMuralAnnotation.subtitle = #"I walk here";
[myMural addObject:myMuralAnnotation];
if(item.tag == 1)
{
//show and hide annotation
NSLog(#"shop");
[mapView addAnnotations:myShop];
[mapView removeAnnotations:myCafe];
[mapView removeAnnotations:myFood];
[mapView removeAnnotations:myMural];
}
if(item.tag == 2)
{
//show and hide annotation
NSLog(#"cafe");
[mapView removeAnnotations:myShop];
[mapView addAnnotations:myCafe];
[mapView removeAnnotations:myFood];
[mapView removeAnnotations:myMural];
}
if(item.tag == 3)
{
//show and hide annotation
NSLog(#"food");
[mapView removeAnnotations:myShop];
[mapView removeAnnotations:myCafe];
[mapView removeAnnotations:myFood];
[mapView addAnnotations:myMural];
}
if(item.tag == 4)
{
//show and hide annotation
NSLog(#"mural");
[mapView removeAnnotations:myShop];
[mapView removeAnnotations:myCafe];
[mapView removeAnnotations:myFood];
[mapView addAnnotations:myMural];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
When removeAnnotations: is called like this:
[mapView removeAnnotations:myCafe];
the map view looks for the exact objects (using pointer comparison) in myCafe that are already on the map.
The map view here does not match up annotations using their coordinate, title, etc.
Since the code creates new instances of each annotation every time a selection is made, the new instances are not found on the map and so removeAnnotations: does nothing.
Instead, in your case, you could just tell the map view to remove all existing annotations and then add the new annotations based on the current selection.
Instead of this:
[mapView addAnnotations:myShop];
[mapView removeAnnotations:myCafe];
[mapView removeAnnotations:myFood];
[mapView removeAnnotations:myMural];
do this:
[mapView removeAnnotations:mapView.annotations]; //remove all
[mapView addAnnotations:myShop]; //then add new
The code could be simplified as well by using a switch statement and in each case, only create the annotations needed for the selection (you don't need to create all annotations every time).
I'm new to iOS, and it's so different from Android logic that I can't find how to add a marker to a map :-|
I've added a MKMapView to my xib
I've added this code to my .m (trimmed)
#import "AppDelegate.h"
#import <MapKit/MapKit.h>
#interface Dove ()
#property (weak,nonatomic) IBOutlet MKMapView *mappa;
#end
#define METERS_PER_MILE 1609.344
#implementation Dove
- (IBAction)vaiHome:(id)sender {
Index *second = [[Index alloc] initWithNibName:#"Index" bundle:nil];
[self presentViewController:second animated:YES completion:nil];
}
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 45.40170;
zoomLocation.longitude= 8.91552;
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, METERS_PER_MILE, METERS_PER_MILE);
[_mappa setRegion:viewRegion animated:YES];
[_mappa regionThatFits:viewRegion];
}
Now, how can I display a pin at that position? It should simple, but I can't find a solution :-|
Also, the map remain in united states but it most go to the marker.
Thanks a lot.
First you have to setup the annotation marker (call this in your viewdidload):
- (void)setupAnnotation
{
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 45.40170;
zoomLocation.longitude= 8.91552;
NARMapViewAnnotation* annot = [[NARMapViewAnnotation alloc] initWithCoord:zoomLocation];
[_mapView addAnnotation:annot];
}
Then you have to setup the MKMapViewDelegate method:
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
MKAnnotationView* annotView = [views objectAtIndex:0];
id<MKAnnotation> mp = [annotView annotation];
MKCoordinateRegion region = [mv regionThatFits:MKCoordinateRegionMakeWithDistance([mp coordinate], REGION_WINDOW, REGION_WINDOW)];
[mv setRegion:region animated:YES];
}
NARMapViewAnnotation:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface NARMapViewAnnotation : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
- (id)initWithCoord:(CLLocationCoordinate2D)coord;
#end
#import "NARMapViewAnnotation.h"
#implementation NARMapViewAnnotation
- (id)initWithCoord:(CLLocationCoordinate2D)coord
{
if (self = [super init])
{
_coordinate = coord;
}
return self;
}
#end
I want to display a map and show the location. My code is running well, but the location could not be displayed on the map. I do not know how to do it.
Well here are my classes:
ViewController.h
#interface ViewController :
UIViewController<AGSMapViewLayerDelegate,CLLocationManagerDelegate>
{
AGSMapView *_mapView;
AGSGraphicsLayer *_graphicsLayer;
AGSTiledMapServiceLayer *_tiledLayer;
CLLocationManager *locationManager;
CLLocation *startingPoint;
}
#property (nonatomic,retain) IBOutlet AGSMapView *mapView;
#property (nonatomic, retain) AGSTiledMapServiceLayer *tiledLayer;
#property (nonatomic, retain) CLLocationManager *locationManager;
#property (nonatomic, retain) AGSGraphicsLayer *graphicsLayer;
#property (nonatomic, retain) CLLocation *startingPoint;
ViewController.m
#interface ViewController()
#end
#implementation ViewController
#synthesize mapView = _mapView;
#synthesize graphicsLayer = _graphicsLayer;
#synthesize tiledLayer = _tiledLayer;
#synthesize locationManager;
#synthesize startingPoint;
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.layerDelegate =self;
self.graphicsLayer = [AGSGraphicsLayer graphicsLayer];
[self.mapView addMapLayer:self.graphicsLayer withName:#"graphicsLayer"];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self; // send loc updates to myself
self.locationManager.distanceFilter = 1000.0f; // 1 kilometer
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
}
- (void)mapViewDidLoad:(AGSMapView *)mapView{
[self.locationManager startUpdatingLocation]; //启用位置监控
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
self.startingPoint = [locations lastObject];
[self.locationManager stopUpdatingLocation]; //获取位置信息
CGPoint coord;
coord.x = startingPoint.coordinate.longitude;
coord.y = startingPoint.coordinate.latitude;
//将坐标用AGSPoint来表示
AGSPoint *mappoint = [[AGSPoint alloc]initWithX:coord.x y:coord.y spatialReference:nil];
//[self.graphicsLayer removeAllGraphics];
AGSPictureMarkerSymbol *pt;
pt = [AGSPictureMarkerSymbol pictureMarkerSymbolWithImageNamed:#"LocationDisplay.png"];
AGSGraphic *LocationDisplay = [[AGSGraphic alloc] initWithGeometry:mappoint symbol:pt attributes:nil infoTemplateDelegate:nil];
// 添加要素到GraphicsLayer
[self.graphicsLayer addGraphic:LocationDisplay];
[self.graphicsLayer refresh];
//漫游到指定级别
[self.mapView centerAtPoint:mappoint animated:YES];
int levelToZoomTo = 12;
AGSLOD* lod = [self.tiledLayer.mapServiceInfo.tileInfo.lods objectAtIndex:levelToZoomTo];
float zoomFactor = lod.resolution/self.mapView.resolution;
AGSMutableEnvelope *newEnv = [AGSMutableEnvelope envelopeWithXmin:self.mapView.visibleAreaEnvelope.xmin
ymin:self.mapView.visibleAreaEnvelope.ymin
xmax:self.mapView.visibleAreaEnvelope.xmax
ymax:self.mapView.visibleAreaEnvelope.ymax
spatialReference:self.mapView.spatialReference];
[newEnv expandByFactor:zoomFactor];
[self.mapView zoomToEnvelope:newEnv animated:YES];
}
You need to provide a spatial reference when you create the AGSPoint from the CLLocation coordinates. Use [AGSSpatialReference wgs84SpatialReference]
If the map is not using WGS84 spatial reference then you need to reproject the point to the map spatial reference before you add it to the map using the geometry engine.
OR
you can use the locationDisplay property built into AGSMapView, by setting mapView.locationDisplay.startDataSource to display your current location.
See the docs for AGSMapView
func mapViewDidLoad(mapView: AGSMapView!) {
//do something now that the map is loaded
//for example, show the current location on the map
mapView.locationDisplay.startDataSource()
}
Try setting mapview.showUserLocation = YES ; or set it in XIB