Mapsearch Reading Essays

Source: Internet
Author: User

Mapsearch

https://developer.apple.com/library/ios/samplecode/MapSearch/Introduction/Intro.html#//apple_ref/doc/uid/DTS40013332

1. #import <MapKit/MapKit.h>//Introduction of header Files
#import <CoreLocation/CoreLocation.h>
Follow the agreement
<cllocationmanagerdelegate, uisearchbardelegate>

2. declaring properties
@interface Mytableviewcontroller ()
@property (nonatomic, assign) mkcoordinateregion boundingregion;
@property (nonatomic, strong) Mklocalsearch *localsearch;
@property (nonatomic, weak) Iboutlet Uibarbuttonitem *viewallbutton;
@property (nonatomic, strong) Cllocationmanager *locationmanager;
@property (nonatomic) cllocationcoordinate2d usercoordinate;
@property (Weak, nonatomic) Iboutlet Uisearchbar *searchbar;

@end

3. Initialize Locationmanager
-(void) Viewdidload {
[Super Viewdidload];

Self.locationmanager = [[Cllocationmanager alloc] init];
}

4. UITableView delegate Methods
-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {
return [self.places Count];
}

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {
UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:kcellidentifier Forindexpath:indexpath];

Mkmapitem *mapitem = [Self.places objectAtIndex:indexPath.row];
Cell.textLabel.text = Mapitem.name;

return cell;
}

5. Click the Search button to execute
-(void) searchbarsearchbuttonclicked: (Uisearchbar *) searchbar{
Check If location Services is available
if ([cllocationmanager locationservicesenabled] = = NO) {
NSLog (@ "%s:location services is not available.", __pretty_function__);

Display alert to the user.
Uialertcontroller *alert = [Uialertcontroller alertcontrollerwithtitle:@ "Location Services"
message:@ "Location Services is not enabled on the this device. Please enable the location services in Settings. "
Preferredstyle:uialertcontrollerstylealert];
uialertaction* DefaultAction = [uialertaction actionwithtitle:@ "Dismiss" Style:uialertactionstyledefault
handler:^ (Uialertaction * action) {}]; Do nothing action to dismiss the alert.

[Alert addaction:defaultaction];
[Self Presentviewcontroller:alert animated:yes completion:nil];

Return
}

//Request "When on use" Location service authorization.
//If authorization have been denied previously, we can display an alert If the user have denied location services prev iously.
if ([cllocationmanager authorizationstatus] = = kclauthorizationstatusnotdetermined) {
[Self.locationmanager Requestwheninuseauthorization];
} else if ([cllocationmanager authorizationstatus] = = kclauthorizationstatusdenied) {
NSLog (@ "%s:location servi Ces authorization was previously denied by the user. ", __pretty_function__);

Display alert to the user.
Uialertcontroller *alert = [Uialertcontroller alertcontrollerwithtitle:@ "Location Services"
message:@ "Location services were previously denied by the user. Please enable the location services for this app in Settings. "
Preferredstyle:uialertcontrollerstylealert];
uialertaction* DefaultAction = [uialertaction actionwithtitle:@ "Dismiss" Style:uialertactionstyledefault
handler:^ (Uialertaction * action) {}]; Do nothing action to dismiss the alert.

[Alert addaction:defaultaction];
[Self Presentviewcontroller:alert animated:yes completion:nil];

Return
}

Start updating locations.
Self.locationManager.delegate = self;
[Self.locationmanager startupdatinglocation];
}

6. Search around locations based on location information after getting location information
-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations {

Remember for later the user's current location.
Cllocation *userlocation = Locations.lastobject;
Self.usercoordinate = userlocation.coordinate;

[Manager Stopupdatinglocation]; We only want one update.

Manager.delegate = nil; We might is called again here, even though we
Called "Stopupdatinglocation", so remove us as the delegate to be sure.

We have a and so start the search.
[Self startSearch:self.searchBar.text];
}

-(void) Startsearch: (NSString *) searchstring {
if (self.localSearch.searching)
{
[Self.localsearch Cancel];
}

Confine the map search area to the user's current location.
Mkcoordinateregion newregion;
NewRegion.center.latitude = Self.userCoordinate.latitude;
NewRegion.center.longitude = Self.userCoordinate.longitude;

Setup the area spanned by the map region:
We use the delta values to indicate the desired zoom level of the map,
(smaller delta values corresponding to a higher zoom level).
The numbers used here correspond to a roughly 8 mi
Diameter area.
//
NewRegion.span.latitudeDelta = 0.112872;
NewRegion.span.longitudeDelta = 0.109863;

Mklocalsearchrequest *request = [[Mklocalsearchrequest alloc] init];

Request.naturallanguagequery = SearchString;
Request.region = newregion;

Mklocalsearchcompletionhandler Completionhandler = ^ (Mklocalsearchresponse *response, NSError *error) {
if (Error! = nil) {
NSString *ERRORSTR = [[Error userInfo] valueforkey:nslocalizeddescriptionkey];
Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Could not find Places"
Message:errorstr
Delegate:nil
cancelbuttontitle:@ "OK"
Otherbuttontitles:nil];
[Alert show];
} else {
Self.places = [response Mapitems];

Used for later when setting the map's region in "Prepareforsegue".
Self.boundingregion = response.boundingregion;

self.viewAllButton.enabled = self.places! = nil? Yes:no;

[Self.tableview Reloaddata];
}
[UIApplication sharedapplication].networkactivityindicatorvisible = NO;
};

if (self.localsearch! = nil) {
Self.localsearch = nil;
}
Self.localsearch = [[Mklocalsearch alloc] initwithrequest:request];

[Self.localsearch Startwithcompletionhandler:completionhandler];
[UIApplication sharedapplication].networkactivityindicatorvisible = YES;
}

7. Click on the corresponding cell or click the ShowAll button to jump to the next screen.
-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) Sender {
Mapviewcontroller *mapviewcontroller = Segue.destinationviewcontroller;

if ([Segue.identifier isequaltostring:@ "ShowDetail"]) {
Get the single item.
Nsindexpath *selecteditempath = [Self.tableview indexpathforselectedrow];
Mkmapitem *mapitem = Self.places[selecteditempath.row];

Pass the new bounding region to the map destination view controller.
Mkcoordinateregion region = self.boundingregion;
and center it on the single placemark.
Region.center = mapItem.placemark.coordinate;
mapviewcontroller.boundingregion = region;

Pass the individual place to our map destination view controller.
Mapviewcontroller.mapitemlist = [Nsarray Arraywithobject:mapitem];

} else if ([Segue.identifier isequaltostring:@ "ShowAll"]) {

Pass the new bounding region to the map destination view controller.
Mapviewcontroller.boundingregion = self.boundingregion;

Pass the list of places found to our map destination view controller.
Mapviewcontroller.mapitemlist = self.places;
}
}

8. Adjust the map to Zoom/center to the annotations we want to show.
[Self.mapview setRegion:self.boundingRegion Animated:yes];


9. We Add the Placemarks to get the "drop" animation.
if (Self.mapItemList.count = = 1) {
Mkmapitem *mapitem = [Self.mapitemlist objectatindex:0];

Self.title = Mapitem.name;

Add the single annotation to our map.
Placeannotation *annotation = [[Placeannotation alloc] init];
Annotation.coordinate = mapItem.placemark.location.coordinate;
Annotation.title = Mapitem.name;
Annotation.url = Mapitem.url;
[Self.mapview addannotation:annotation];

We have only one annotation, select it ' s callout.
[Self.mapview selectannotation:[self.mapview.annotations objectatindex:0] animated:yes];
} else {
Self.title = @ "All Places";

ADD all the found annotations to the map.

For (Mkmapitem *item in self.mapitemlist) {
Placeannotation *annotation = [[Placeannotation alloc] init];
Annotation.coordinate = item.placemark.location.coordinate;
Annotation.title = Item.name;
Annotation.url = Item.url;
[Self.mapview addannotation:annotation];
}
}

10.
-(void) Mapviewdidfailloadingmap: (Mkmapview *) Mapview witherror: (nserror *) Error {
NSLog (@ "Failed to load the map:%@", error);
}

-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (id <MKAnnotation>) annotation
{
Mkpinannotationview *annotationview = nil;

if ([Annotation iskindofclass:[placeannotation class]]) {
Annotationview = (Mkpinannotationview *) [Self.mapview dequeuereusableannotationviewwithidentifier:@ "Pin"];

if (Annotationview = = nil) {
Annotationview = [[Mkpinannotationview alloc] initwithannotation:annotation reuseidentifier:@ "Pin"];
Annotationview.canshowcallout = YES;
Annotationview.animatesdrop = YES;
}
}
return annotationview;
}

11. Removeannotations when the interface is going to disappear
-(void) Viewdiddisappear: (BOOL) Animated {
[Super viewdiddisappear:animated];
[Self.mapview removeAnnotations:self.mapView.annotations];
}

Mapsearch Reading Essays

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.