iOS Development-Location services and GEO fencing

Source: Internet
Author: User
Tags reverse geocoding

First, get the user's location
Use the Corelocation framework.
1. If your app is based on location to run correctly, you should include the Uirequireddevicecapabilities key in your info.plist. The App Store uses this information to prevent devices that are not located from downloading the app.
The Uirequireddevicecapabilities key corresponds to an array of strings, including:
1) Location-services string--if you request a general location service
2) gps--If you request GPS-grade accuracy
Do not include this key if your application needs to be positioned but not positioned to function properly.

2, access to the user's positioning
There are 2 ways to do this:
1) Standard location Services
2) Significant Position Change location service: only valid after 4.0.


3. Determine if location services are available:
1) Users can disable location services in the Setup program
2) Users can deny location services to an app
3) The device may be in airplane mode, and the required hardware cannot be enabled.
For these reasons, it is recommended that you call[Cllocationmanager locationservicesenabled]To determine if location services are available.
Use[Cllocationmanager authorizationstatus]==kclauthorizationstatusdeniedCheck if location services are prohibited by this app.


4, start the standard location service:
Cllocationmanager *locationmanager = [[Cllocationmanager alloc] init];
Locationmanager.delegate = self;
Locationmanager.desiredaccuracy = Kcllocationaccuracykilometer;
Set a movement threshold for new events.
Locationmanager.distancefilter = 500;
[Locationmanager startupdatinglocation];


5. Start Significant-change location Service:
[Locationmanager startmonitoringsignificantlocationchanges];
After you start this service, you can receive notifications even when the app is not started, and go into the background state to handle events. But you can't let the program's background task exceed 10 minutes.

6. Receive location data from the service
locationManager:didUpdateToLocation:fromLocation
Locationmanager:didfailwitherror:


7, monitoring shape-based regions:
after iOS4.0, apps can use region monitoring to be notified when a user crosses a geographic boundary. This notification can be received even if the app is not started, and goes into the background state to handle the event. (inference: Should andstartmonitoringsignificantlocationchanges, do not allow the program's background task to exceed 10 minutes)

8. Determine the availability of region monitoring
There are several reasons why region monitoring may not be available:
1) The device may not have hardware to support region monitoring
2) The user may have disabled location services
3) The device may be in flight mode.
Therefore, you need to call[Cllocationmanager regionmonitoringavailable] and [Cllocationmanager regionmonitoringenabled]To determine if it is available.

9. Define a region to monitor:
To monitor an area, you need to define a region and register it with the system. Regions is defined using the Clregion class and supports creating a circular area. The region you create must include the data for the geographic area and a unique flag string. To register a region, you need to call the Cllocationmanager object's startmonitoringforregion:desiredaccuracy: method.
Example:
If regionmonitoring is not supported, do not create region.
if (![ Cllocationmanager Regionmonitoringavailable] | |
! [Cllocationmanager regionmonitoringenabled])
return NO;

If the radius is too large, the registration will fail automatically, so when the radius is too large, set it to the maximum value
Cllocationdegrees radius = Overlay.radius;
if (Radius > Self.locManager.maximumRegionMonitoringDistance)
radius = self.locManager.maximumRegionMonitoringDistance;

Create a region and start monitoring it
clregion* region = [[Clregion alloc] initCircularRegionWithCenter:overlay.coordinate Radius:radius identifier: Identifier];
[Self.locmanager startmonitoringforregion:region desiredaccuracy:kcllocationaccuracyhundredmeters];

[Region release];

...
Start monitoring region immediately after registering, but don't expect to get an event right away. Events are generated only when crossing boundaries. Therefore, if the user's location is already within the zone at the time of registration, the Locationmanager does not produce an event.
You have to use regions monitoring wisely. Regions is a system-sharing resource, and its number is capped. Therefore, the Core location restricts the number of regions that an application listens to simultaneously. You should consider listening only to the region where the user is located, and when the user's position changes, you can remove the distant regions and add a nearby regions to listen. If you try to register a region and there is no space, Locationmanager will call LocationManager:monitoringDidFailForRegion:withError: method, and pass a kclerrorregionmonitoringfailure error code.

10. Handling cross Border events in region
locationmanager:didenterregion:
Locationmanager:didexitregion:


11.get location events in the background
There are several ways:
1)using the Signicant location Change service: [Locationmanager startmonitoringsignificantlocationchanges];
2) Use the standard location service: Specify the position in the Uibackgroundmode key in the Info.plist


12. Tips for protecting battery power
1) Close the location service when you do not need to locate:
2) Use Significant-change location service
3) Use low-precision desired accuracy
4) If the polling service is periodic, then close the location service in the middle of the cycle

TwoGet direction-related events
Core location supports two ways to obtain orientation-related information:
1) A device with a magnetometer (magnetometer) can report the direction the device is pointing to, also known as heading.
2) devices with GPS can report the direction of device movement, also known as course.

Remember that heading and course do not represent the same information.

1, if your application needs direction-related information to run correctly, you need to specify the Uirequireddevicecapabilities key in Info.plist, whose value is an array of strings, including:
1) magnetometer---corresponding heading
2) gps--corresponding course

2. Get heading-related event: Steps:
1) Instantiating Cllocationmanager objects
2) OK [Cllocationmanager headingavailable]
3) Specify the agent
4) If you want to get the true North values, you need to enable standard services
5) Call startupdatingheading to start posting heading event

The following example:
cllocationmanager* Locmanager = [[[[Cllocationmanager alloc] init] autorelease];
Locmanager.delegate = self;

Start Location Services to get the true heading.
Locmanager.distancefilter = 1000;
Locmanager.desiredaccuracy = Kcllocationaccuracykilometer;
[Locmanager startupdatinglocation];

Start heading updates.
if ([Cllocationmanager headingavailable]) {
Locmanager.headingfilter = 5;
[Locmanager startupdatingheading];
}


Agent Function: locationmanager:didupdateheading: Method.
Once you receive a new event, you need to check the Headingaccuracy property to make sure the data is valid. Also, if you are using true heading value, you should check to see if it contains a valid value before using it.
-(void) Locationmanager: (Cllocationmanager *) Manager didupdateheading: (clheading *) newheading {
if (newheading.headingaccuracy < 0)
Return

Use the true heading if it is valid.
Cllocationdirection theheading = ((newheading.trueheading > 0)? newHeading.trueHeading:newHeading.magneticHeading );
self.currentheading = theheading;
[Self updateheadingdisplays];

}

3. Get course information when the user moves
Devices that have GPS hardware can generate information about the current course and speed of the device. Crouse information is used to indicate the direction in which the device is moving and does not need to reflect the direction of the device itself. Therefore, it is mainly used for navigation.
The actual course and speed messages are returned in the Cllocation object.
Newlocation.speed
Newlocation.course


Iii. geo-coded position data Geocoding location:
1, about Geocoder object:
A Geocoder object uses a network service to convert between (longitude, latitude) and landmarks, a collection of data, such as street, City, state, and country information. Reverse geocoding (Inverse geocoding) is the conversion (longitude, latitude) to a landmark. Forward geocoding (positive geocoding) is the conversion of Location name information to (longitude, latitude) values. Inverse geocoding is available in all iOS versions, but positive geocoding is only supported after iOS5.0.
Because the GeoCode service requires a network, if the device is in flight mode or the device does not currently have a network, the Geocoding object cannot connect to the service it needs, so it will definitely return an error.

2. Convert coordinates to place name information:
In iOS, you can use the Clgeocoder class to handle inverse geocoding. Mkreversegecoder was discarded after iOS5.0.

3.use Clgeocoder to get landmark information
Creates an instance of the Clgeocoder class and invokes the
[Gecoder Reversegeocodelocation:completionhandler:] Method
Example:

Clgeocoder *gecoder=[[clgeocoder Alloc]init];
[Geocoder reversegeocodelocation:location completionhandler:^ (nsarray *placemarks,nserror *error) {
if ([Placemarks count]>0) {
Annotation.placemark=[placemark objectatindex:0];
...
}
}];

...

4. Get landmark information from reverse Geocoder:
Mkreversegeocoder *thegeocoder=[[mkreversegeocoder Alloc]initwithcoordinate:location.coordinate];
thegeocoder.delegate=self;
[Thegeocoder start];

The proxy functions are:
-(void) Reversegeocoder: (Mkreversegeocoder *) Geocoder Didfindplacemark: (Mkplacemark *) place
-(void) Reversegeocoder: (Mkreversegeocoder *) Geocoder didfailwitherror: (nserror *) error

5.convert place names to coordinate
[Geocoder gecodeaddressstring:@ "1 Infinite Loop" completionhandler:^ (Nsarray *placemarks,nserror *error) {
For (Clplacemark *aplacemark in Placemarks) {
Clplacemark objects contain geo-location information, including latitude and longitude, of course
}
}];


Iv. Show Map
MAP Kit Framework
1. Understanding Map Geometry
A map view is flattened to represent a spherical object-the Earth. You need to know something about how to specify points in a map view, and how these points are converted to the Earth's surface coordinates. It is important to understand the map coordinate system if you intend to prevent custom content, such as overlays, from being on the map.

2. Map coordinate system
How does the three-dimensional coordinates of the earth be mapped to the two-dimensional coordinates of the map?
Map Kit uses Mercator mapping.
How you specify the data points on the map depends on how you intend to use them. The map kit supports the basic coordinate system in 3 to specify the mapping data points:
1) A map coordinate: is the spherical representation of the map (longitude, latitude). The primary method of map coordinate system is to specify the position on the earth. Use the CLLOCATIONCOORDINATE2D structure. Use the Mkcoordinatespan and mkcoordinateregion structures to specify the area.
2) A map point: Is the (x, y) dot after Mercator map mapping. Use map points to calculate map-related calculations, rather than map coordinates, because they simplify calculations. In your application, you primarily use map point to specify the position of shape and custom overlay. Use the MKMAPPOINT structure. Use the mkmapsize and Mkmaprect structures to specify the area.
3) A point is a graphical unit in the UIView coordinate system. Map Piont and map coordinate must be mapped to point before the contents of the view are drawn. Use Cgpoint,cgsize and CGRect.
In most cases, the coordinate system you should use depends on the map kit interface you want to use. Map coordinate is preferred when you want to store the actual data in the file.
The Core location also uses the map coordinate to specify the position value.

3. Conversion between coordinate systems:
Convert from convert to Conversion routines
Map coordinate Points Convertcoordinate:topointtoview: (Mkmapview)
Convertregion:torecttoview: (Mkmapview)
Map coordinate map Points mkmappointforcoordinate
Map Points Map coordinates mkcoordinateformappoint
Mkcoordinateregionformaprect
Map Points Points pointformappoint: (Mkoverlayview)
Rectformaprect: (Mkoverlayview)
Points MAP coordinates Convertpoint:tocoordinatefromview: (Mkmapview)
Convertrect:toregionfromview: (Mkmapview)
Points Map Points mappointforpoint: (Mkoverlayview)
Maprectforrect: (Mkoverlayview)


4. Add a map view to the user interface
Mkmapview
5. Configure map Properties
1)to set the visible part of a map: Region property, is a mkcoordinateregion structure
typedef struct {
Cllocationcoordinate2d Center;
Mkcoordinatespan span;
} mkcoordinateregion;
The interesting thing is span. span is similar to the width and height values of a rectangle, but is specified by the map coordinate, so it is measured by degree (degrees), minutes (minutes), seconds (seconds). Latitude (latitude) was once about 111km, but longitude (longitude) was once different from latitude. At the equator, the longitude is approximately 111km, but at the pole, the value is 0. If you choose to use meters to specify span, you can usemkcoordinateregionmakewithdistanceTo create a region data structure, using meters instead of degrees.
The value of the region attribute you specify (or use the setregion:animated: method) is usually different from the value that is actually stored in the property. Setting span for region only defines the rectangle you want to view, but it also implicitly sets the zoom level of the map view. Map view cannot display any zoom level, and you must adjust the region you set to match the zoom level that it supports. It chooses to hold your entire region visible while at the same time filling the screen with the zoom level as much as possible. Accordingly, it then adjusts the region property. To find the result of region without actually changing the properties of region, you can use the Regionthatfits: method of the Map view.

2)scale and panning map content:
A) Pan map: Change the value of the Centercoordinate property or setcentercoordinate:animated: Method
b) Change the zoom level: Change the value of the region attribute or setregion:animated: Method

If you just want a pan map, you need to use the first method, and if you change the center property of the region property, it usually causes the zoom level to change.

Cllocationcoordinate2d mapcenter = mymapview.centercoordinate;
Mapcenter = [Mymapview convertpoint:cgpointmake (1, (mymapview.frame.size.height/2.0)) Tocoordinatefromview: Mymapview];
[Mymapview Setcentercoordinate:mapcenter Animated:yes];


To zoom the map, modify the span of region, to zoom in, set a smaller value to span, and to zoom out, set a larger value to span.
mkcoordinateregion theregion = mymapview.region;
Zoom out
TheRegion.span.longitudeDelta *= 2.0;
TheRegion.span.latitudeDelta *= 2.0;
[Mymapview setregion:theregion Animated:yes];


3)show the user's current location on the map
Set the Showsuserlocation property to Yes
。 Doing so causes map view to use the core location to find the user's position and add a mkuserlocation type of annotation to the map.

6. Respond to user interactions with maps
Mkmapview reports significant map-related events to its agents. The agent follows the Mkmapviewdelegate protocol. You can respond to the following events:
1) Change the visible region of the map
2) Loading map fragments from the network
3) Change the user's location
4) Change the relevant annotation and overlay

Five, annotating Maps
1.add annotations to your map:
To implement this, you must provide two objects:
1) objects that comply with the Mkannotation protocol (that is, annotation objects)
2) A view that inherits from the Mkannotationview class and is used to draw Annoatation's performance (and annotation view)

The MAP kit provides some standard annotation views, and you can define your own annotation.

2.Add annotation to the list on the map:
1) Define an appropriate annotation object, using the following options:
A) Use the Mkpointannotation class to implement a simple annotation.
b) Define a custom object that follows the Mkannotation protocol
2) Define a annotation view to represent the data on the screen.
A) If annotation can be represented by a static image, create an instance of the Mkannotationview class and specify the Image property
b) If you want to use a standard annotation, create an instance of the Mkpinannotationview class
c) If the static image is inappropriate, then subclass the Mkannotationview and implement the custom draw code.
3) Implement Mapview:viewforannotation: Method---in your mapview agent. and returns a Annotationview.
4) Use addannotation: or Addannotations: method to add the Addnotation object.


3. Define a custom annotation object
Mainly comply with the Mkannotation Agreement:
Must have coordinate read-only property

4, using the standard annotation views:
Mkannotationview and Mkpinannotationview (subclass of Mkannotationview)
The Mkannotationview is suitable for displaying only one image. With the Image property, you can also specify the Centeroffset property to move the center point.

5. Define your own annotation View
Subclass Mkannotationview, you can continue to use the Image property and overload the DrawRect: method.

6. Create annotation views in the agent
-(Mkannotationview *) Mapview: (Mkmapview *) Mapview viewforannotation: (ID) annotation{
}

7, manage the map annotation object:
You can add and remove annotations in mapview:regionwillchangeanimated: and mapview:regiondidchangeanimated: Methods
After iOS4.0, you can use the Mkmetersbetweenmappoints method to get an absolute distance between two points. You can also use the Mkmaprectintersetsrect function to find any intersection.

8. Mark your annotationview to be draggable:
1) in your annotation object, implement the Setcoordinate: method to allow the map view to update the coordinate point of the annotation.
2) set its Draggable property to Yes.

When the user drags annotation, the delegate receives the MapView:annotationView:didChangeDragState:fromOldState: method


9.Show overlay on the map:
Similar to the annotation:
1) objects that need to implement the Mkoverlay protocol (that is, the overlay object)
2) A view (inherited from the Mkoverlayview class) (i.e. overlay view)

10. Add overlay to the list of maps:
1) Define a overlay object:
A) Use Mkcircle, Mkpolygon, mkpolyline, etc.
b) Subclass Mkshape or Mkmultipoint to create a custom overlay object.
c) Use an existing class and comply with the Mkoverlay protocol.
2) Define a overlay view:
A) for standard graphics, use Mkcircleview, Mkpolygonview, Mkpolylineview
b) For custom shapes that inherit from Mkshape, define a subclass of the appropriate mkoverlaypathview to render the shape.
c) For other custom shapes and overlay, subclass Mkoverlayview and implement DrawRect: Method
3) Implement proxy function: Mapview:viewforoverlay: and return Mkoverlayview
4) Add overlay using Addoverlay: Method


11. Use standard overlay objects and views:
Mkcircle, Mkpolygon, Mkpolyline are overlay objects.
Mkcircleview, Mkpolygonview, Mkpolylineview are overlay views.

12. Define a custom overlay object:
Subclass Mkshape or Mkmultipoint or adopt Mkoverlay protocol.
1) must have coordinate readable properties
2) A bounding rectangle, completely containing the contents of overlay.

13. Define a custom overlay view:
Subclass Mkoverlayview, and overloads
DrawMapRect:zoomScale:inContext:
Candrawmaprect:zoomscale:

14. Create a overlay view from the agent
Mapview:viewforoverlay: Method

15, manage the map overlay object:
Overlays Property
The Proxy function Mapview:didaddoverlayviews: method, and then use the Mkmaprectintersectsrect function to see if the overlay you have added has an intersection with its overlay.

16.Use overlay as annotations
The Mkoverlay protocol follows the Mkannotation protocol. As a result, all overlay objects can be used as annotation objects

iOS Development-Location services and GEO fencing

Related Article

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.