Mkmapview and mkmapviewdelegate

Source: Internet
Author: User
@ Interface mkmapview: uiview <nscoding> @ property (nonatomic, assign) ID <mkmapviewdelegate> delegate; // changing the map type or region can cause the map to start loading map content. // The loading delegate methods will be called as map content is loaded. /* Enum {mkmaptypestandard, mkmaptypesatellite, mkmaptypehybrid}; */@ property (nonatomic) mkmaptype maptype; // region is the coordinate and span of the map. // region may be modified to fit the aspect ratio (screen aspect ratio) of the view using regionthatfits :. @ property (nonatomic) mkcoordinateregion region;-(void) setregion :( mkcoordinateregion) region animated :( bool) animated; // centercoordinate allows the coordinate of the region to be changed without changing the zoom level. /* typedef struct {cllocationdegrees latitude; // latitude cllocationdegrees longpolling; // longitude} longitude; * // @ property (nonatomic) extends centercoordinate;-(void) setcentercoordinate :( longitude) coordinate animated :( bool) animated; // returns a region of the aspect ratio of the map view that contains the given region, with the same center point. /* adjusts the aspect ratio of the specified region to ensure that it fits in the map view's frame. you can use this method to normalize the region values before displaying them in the map. this methodreturns a new region that both contains the specified region and fits neatly inside the map view's frame. */-(mkcoordinateregion) regionthatfits :( mkcoordinateregion) region; // access the visible region of the map in projected coordinates. @ property (nonatomic) mkmaprect visiblemaprect;-(void) Submit :( mkmaprect) maprect animated :( bool) animate; // returns an mkmaprect modified to fit the aspect ratio of the map. -(mkmaprect) maprectthatfits :( mkmaprect) maprect; // edge padding is the minumum padding on each side around the specified mkmaprect. -(void) Grouping :( mkmaprect) maprect grouping :( uiedgeinsets) insets animated :( bool) animate;-(mkmaprect) Grouping :( mkmaprect) maprect grouping :( uiedgeinsets) insets;-(cgpoint) convertcoordinate :( partial) Coordinate topointtoview :( uiview *) view;-(partial) convertpoint :( cgpoint) Point tocoordinatefromview :( uiview *) view;-(cgrect) convertregion :( partial) region torecttoview :( uiview *) view;-(mkcoordinateregion) convertrect :( cgrect) rect toregionfromview :( uiview *) view; // Disable User Interaction from zooming or scrolling the map, or both. @ property (nonatomic, Getter = iszoomenabled) bool zoomenabled; @ property (nonatomic, Getter = isscrollenabled) bool scrollenabled; // set to yes to add the user location annotation to the map and start updating its location @ property (nonatomic) bool showsuserlocation; // The annotation representing the user's location @ property (nonatomic, readonly) mkuserlocation * userlocation;/* Enum {mkusertrackingmodenone = 0, // The user's location is not followed mkusertrackingmodefollow, // The map follows the user's location mkusertrackingmodefollowwithheading, // The map follows the user's location and heading }; * // @ property (nonatomic) mkusertrackingmode usertrackingmode ns_available (Na, 5_0);-(void) setusertrackingmode :( mkusertrackingmode) mode animated :( bool) animated Merge (Na, 5_0 ); // returns yes if the user's location is displayed within the currently visible map region. @ property (nonatomic, readonly, Getter = isuserlocationvisible) bool userlocationvisible; // annotations are models used to annotate coordinates on the map. // implement mapview: viewforannotation: On mkmapviewdelegate to return the annotation view for each annotation. -(void) addannotation :( id <mkannotation>) annotation;-(void) addannotations :( nsarray *) annotations;-(void) removeannotation :( id <mkannotation>) annotation; -(void) removeannotations :( nsarray *) annotations; @ property (nonatomic, readonly) nsarray * annotations;-(nsset *) Events :( mkmaprect) maprect ns_available (Na, 4_2 ); // currently displayed view for an annotation; returns nil if the view for the annotation isn't being displayed. -(mkannotationview *) viewforannotation :( id <mkannotation>) annotation; // used by the delegate to acquire an already allocated annotation view, in lieu of allocating a new one. -(mkannotationview *) dequeuereusableannotationviewwithidentifier :( nsstring *) identifier; // select or deselect a given annotation. asks the delegate for the corresponding annotation view if necessary. -(void) selectannotation :( id <mkannotation>) annotation animated :( bool) animated;-(void) deselectannotation :( id <mkannotation>) annotation animated :( bool) animated; @ property (nonatomic, copy) nsarray * selectedannotations; // annotationvisiblerect is the visible rect where the annotations views are currently displayed. // The delegate can use annotationvisiblerect When animating the adding of the annotations views in mapview: didaddannotationviews: @ property (nonatomic, readonly) cgrect annotationvisiblerect; @ end

@protocol MKMapViewDelegate <NSObject>@optional- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated;- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView;- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView;- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error;// mapView:viewForAnnotation: provides the view for each annotation.// This method may be called for all or some of the added annotations.// For MapKit provided annotations (eg. MKUserLocation) return nil to use the MapKit provided annotation view.- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;// mapView:didAddAnnotationViews: is called after the annotation views have been added and positioned in the map.// The delegate can implement this method to animate the adding of the annotations views.// Use the current positions of the annotation views as the destinations of the animation.- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views;// mapView:annotationView:calloutAccessoryControlTapped: is called when the user // taps on left & right callout accessory UIControls.- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control;- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view NS_AVAILABLE(NA, 4_0);- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view NS_AVAILABLE(NA, 4_0);//Tells the delegate that the map view will start tracking the user’s position.//This method is called when the value of the showsUserLocation property changes to YES.- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView NS_AVAILABLE(NA, 4_0);//Tells the delegate that the map view stopped tracking the user’s location.//This method is called when the value of the showsUserLocation property changes to NO.- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView NS_AVAILABLE(NA, 4_0);//Tells the delegate that the location of the user was updated./*1. a new location update is received by the map view.  2. This method is also called if the map view’s user tracking mode      is set to MKUserTrackingModeFollowWithHeading and the heading changes.*/- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation NS_AVAILABLE(NA, 4_0);- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error NS_AVAILABLE(NA, 4_0);- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState    fromOldState:(MKAnnotationViewDragState)oldState NS_AVAILABLE(NA, 4_0);- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay NS_AVAILABLE(NA, 4_0);// Called after the provided overlay views have been added and positioned in the map.- (void)mapView:(MKMapView *)mapView didAddOverlayViews:(NSArray *)overlayViews NS_AVAILABLE(NA, 4_0);- (void)mapView:(MKMapView *)mapView didChangeUserTrackingMode:(MKUserTrackingMode)mode animated:(BOOL)animated NS_AVAILABLE(NA, 5_0);@end

1. Overview

Insert mapview and set delegate (usually Controller). Annotations records the interest location points (annotationview is used to display the interest location points). annotation is optional. The Selected Annotation displays callout, used to display information.

2. Set the map display type:

mapView.mapType = MKMapTypeStandard;mapView.mapType = MKMapTypeSatellite;mapView.mapType = MKMapTypeHybrid; 

3. Display User location

Set to display user location: mapview. showsuserlocation = yes; check whether the current user location is visible (read-only attribute): userlocationvisible get the user location coordinates: cllocationcoordinate2d coords = mapview when userlocationvisible is yes. userlocation. location. coordinate;

4. Coordinate range

Mkcoordinateregion is used to set the coordinate display range. Includes two parts:. center (cllocationcoordinate2d struct, including latitude and longpolling), coordinate center B. span (mkcoordinatespan struct, including latitudedelta and longitudedelta), scaling level // create a center-centered area with 1000 metres up and down, and 1000 metres left and right, but it is a rectangle, the horizontal and vertical ratios of mapview mkcoordinateregion viewregion = align (center, 2000,200 0); // The code above creates a region that matches the horizontal and vertical ratios of mapview. adjustedregion = [mapview regionthatfits: viewregion]; // The code above is: The final display of the region [mapview setregion: adjustedregion animated: Yes];

5. Delegate

Mapview must comply with mkmapviewdelegate protocol 5.1. Map loading delegate when a new map needs to be obtained from the Google server mapviewwillstartloadingmap: After the map is obtained successfully, mapviewdidfinishloadingmap: when a map fails to be obtained (at least this method is recommended) mapviewdidfailloadingmap: witherror: 5.2, range change delegate when the gesture starts (drag, zoom in, zoom out, double-click) mapview: regionwillchangeanimated: when the gesture ends (drag, zoom in, zoom out, double-click) mapview: regiondidchangeanimated: determines whether the coordinates are within the mapview display range: cllocationdegrees leftdegrees = mapview. region. center. longpolling-(mapview. region. span. longitudedelta/2.0); cllocationdegrees rightdegrees = mapview. region. center. longpolling + (mapview. region. span. longitudedelta/2.0); cllocationdegrees bottomdegrees = mapview. region. center. latitude-(mapview. region. span. latitudedelta/2.0); cllocationdegrees topdegrees = self. region. center. latitude + (mapview. region. span. latitudedelta/2.0); If (leftdegrees> rightdegrees) {// Int 'l date line in view leftdegrees =-180.0-leftdegrees; If (coords. longpolling> 0) // coords to west of Date Line coords. longpolling =-180.0-coords. longpolling;} If (leftdegrees <= coords. longpolling & coords. longpolling <= rightdegrees & bottomdegrees <= coords. latitude & coords. latitude <= topdegrees) {// coordinates are in the range}

6. Annotation

Annotation consists of two parts: annotation object and annotation viewannotation object must comply with the mkannotation protocol, including two methods: Title and subtitle, respectively used to display the comment title and subtitle. The coordinate attribute is also returned. cllocationcoordinate2d indicates the location of Annotation. Then, mapview: viewforannotation: is used to return mkannotationview or mkannotationview subclass to display annotation (note: this is not the pop-up box after annotation is selected. You can subclass mkannotationview, and then perform drawrect: You can instantiate a mkannotationview in the method (this method is stupid, then modify its image attribute, which is very simple.

7. add and remove Annotation

Add an annotation [mapview addannotation: annotation]; add an annotation array [mapview addannotations: [nsarray Annotations: annotation1, annotation2, nil]; remove a comment: remove an annotation array removeannotations: remove all annotation [mapview removeannotations: mapview. annotations];

8. Select Annotation

Only one annotation can be selected at a time. After selection, a simple callout (floating box) displays the title and subtitle, however, you can also customize a uiview as callout (the same as the custom tableviewcell). You can select annotation: selectannotation: animated: or deselect deselectannotation: animated:

9. Display Annotation

Through mapview: viewforannotation: The method shows annotation. This method is called every time an annotation is added to mapview (similar to tableview: cellforrowatindexpath:)-(mkannotationview *) mapview :( mkmapview *) themapview viewforannotation :( id <mkannotation>) annotation {static nsstring * identifier = @ "My annotation identifier"; if ([annotation iskindofclass: [myannotation class]) {mkannotationview * annotationview = [themapview comment: Comment]; If (annotationview = nil) {annotationview = [[[mkannotationview alloc] Comment: annotation reuseidentifier: Comment]; annotationview. image = [uiimage imagenamed: @ "blood_orange.png"];} else annotationview. annotation = annotation; return annotationview;} return nil ;}

10. Obtain the real address

Example: Initialize mkreversegeocodermkreversegeocoder * geocoder = [[mkreversegeocoder alloc] initwithcoordinate: Coordinates]; geocoder. delegate = self; [geocoder start]; If coordinates cannot be processed, call reversegeocoder: handle: method-(void) reversegeocoder :( mkreversegeocoder *) geocoder didfailwitherror :( nserror *) error {nslog (@ "error resolving coordinates: % @", [error localizeddescription]); geocoder. delegate = nil; [geocoder autorelease];} If successful, call reversegeocoder: Future: and store the information in mkplacemark. Principal :( mkplacemark *) placemark {nsstring * streetaddress = placemark. thoroughfare; nsstring * city = placemark. locality; nsstring * State = placemark. administrativearea; nsstring * zip = placemark. postalcode; // do something with information geocoder. delegate = nil; [geocoder autorelease];}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.