collect 2 arrays CLLocationDegree in one array of CLLocationCoordinate2D - ios

I need to draw a polyline on google maps on ios , I have latitudes and longitudes in seperated arrays and I want to collect them in one array of CLLocationCoordinate2D, so plz help me to write the code that make this collection

CLLocationCoordinate2D *coords = malloc(coordinateCount * sizeof(CLLocationCoordinate2D));
for(size_t i = 0; i < coordinateCount; ++i)
{
coords[i].latitude = latitudes[i];
coords[i].longitude = longitudes[i];
}
// ... Use the array ...
free(coords);

Related

How to check if anyone is enter/left in/from particular boundary area even if application is in background mode or kill mode?

I want to check if anyone enter in allocated boundary then i have to alert that user like "You are entered" and when user leaves then "You left". I am using .KML file for draw boundary in which there are more than latitude and longitude. Here i attached screenshot for the same.So, my concern is that how can i detect that anyone is entered within this boundary and left from that boundary. Thank you in advance
Boundary looks like this.Red color line is boundary.
Use map rects. Here's an example using the map's current visible rect. With regards to your question, you could use convertRegion:toRectToView: to first convert your region to a MKMapRect beforehand.
MKMapPoint userPoint = MKMapPointForCoordinate(mapView.userLocation.location.coordinate);
MKMapRect mapRect = mapView.visibleMapRect; // find visible map rect
//MKMapRect mapRect = [self getMapRectUsingAnnotations:arrCordinate];//find custom map rect
BOOL inside = MKMapRectContainsPoint(mapRect, userPoint);
MKMapRect mapRect = mapView.visibleMapRect;
Create your custom mapRect using your boundary region from multiple latitude and longitude
- (MKMapRect) getMapRectUsingAnnotations:(NSArray*)arrCordinate {
MKMapPoint points[[arrCordinate count]];
for (int i = 0; i < [arrCordinate count]; i++) {
points[i] = MKMapPointForCoordinate([arrCordinate[i] MKCoordinateValue]);
}
MKPolygon *poly = [MKPolygon polygonWithPoints:points count:[arrCordinate count]];
return [poly boundingMapRect];
}
Geofencing will not work on complex polygon shaped regions. May be you can solve the problem with some other approach. For instance divide the region into smaller CLCircularRegion and then develop aggregate logic for the case where you have to show notification for all those locationManager:didEnterRegion: and locationManager:didExitRegion: callbacks. But keep in mind that only a max of 20 simultaneous monitored regions per app are allowed.
Refer https://forums.developer.apple.com/thread/21323 phillippk1 suggestion for other possible approach.
Try this code. This is based on Winding Number Algorithm. This works for complex shapes such as your red line.
typedef struct {
double lon;
double lat;
} LATLON;
// returns true if w/in region
bool chkInRegion(LATLON poi, int npoi, LATLON *latlon)
{
int wn = 0;
for (int i = 0 ; i < npoi-1 ; i++) {
if (latlon[i].lat <= poi.lat && latlon[i+1].lat > poi.lat) {
double vt = (poi.lat - latlon[i].lat)/(latlon[i+1].lat - latlon[i].lat);
if (poi.lon < (latlon[i].lon + (vt * (latlon[i+1].lon - latlon[i].lon)))) {
wn++;
}
} else if (latlon[i].lat > poi.lat && latlon[i+1].lat <= poi.lat) {
double vt = (poi.lat - latlon[i].lat)/(latlon[i+1].lat - latlon[i].lat);
if (poi.lon < (latlon[i].lon + (vt * (latlon[i+1].lon - latlon[i].lon)))) {
wn--;
}
}
}
return wn < 0;
}
// test data
LATLON llval[] = {
{100,100},
{200,500},
{600,500},
{700,100},
{400,300},
{100,100}
};
#define NLATLON (sizeof(llval)/sizeof(LATLON))
int main(int argc, char **argv) {
while (1) {
char buf[1024];
fprintf(stderr, "lon = ");
fgets(buf, sizeof(buf), stdin);
double lon = atof(buf);
fprintf(stderr, "lat = ");
fgets(buf, sizeof(buf), stdin);
double lat = atof(buf);
LATLON ltest;
ltest.lat = lat;
ltest.lon = lon;
if (chkInRegion(ltest, NLATLON, llval)) {
fprintf(stderr, "\n*** in region ***\n\n");
} else {
fprintf(stderr, "\n=== outside ===\n\n");
}
}
return 0;
}

convert NSMutableArray to CGPoint Array

the typical answer will be "you can convert it to nsvalue and then use [element CGPointValue];
but in my case i need to generate array of type CGPoint , as i need it in a built in function below :
static CGPathRef createClosedPathWithPoints(const CGPoint *points, size_t count) {
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddLines(path, NULL, points, count);
CGPathCloseSubpath(path);
return path;
}
so , i need to pass the exact datatype , as i can't parse it element by element , or i need a way to everytime the user make a specific action , i add it's CGPoint to array of CGPoints :((
thanks in advance
edit :
i have tried malloc and making c array but the result of the function was not desirable , i tested and made infinity for loop to that malloc array , and it's too large not just like the size i sat , and contain garbage so the result went wrong
this is the mutable array
pointToPoints = [NSMutableArray new];
[pointToPoints addObject:[NSValue valueWithCGPoint:tempPoint] ];
Here is something that will create a closed path from an NSArray of NSValue created with CGPoint using the code your provided:
BOOL isCGPoint(NSValue *value){
return value && strcmp([value objCType], #encode(CGPoint)) == 0;
}
- (CGPathRef) closedPathFromPointArray:(NSArray *)points{
CGMutablePathRef path = CGPathCreateMutable();
if(points.count){
CGPoint origin = ((NSValue *)points[0]).CGPointValue;
CGPathMoveToPoint (path, NULL, origin.x, origin.y);
// see https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CGPath/#//apple_ref/c/func/CGPathAddLines
for(NSValue *value in points){
CGPathAddLineToPoint (path, NULL, value.CGPointValue.x, value.CGPointValue.y);
}
}
CGPathCloseSubpath(path);
return path;
}
As you see, you don't really need malloc, or even creating a C array of CGPoint. This assumes you only need this array for creating the closed path.
Two extra things of note:
See the commented link for CGPathAddLines, as it describes how CGPathAddLines works internally. This gives you the hint about how to go about this.
The isCGPoint function is included so you can test if a given NSValue instance was actually created using [NSValue valueWithCGPoint:]. My previous answer checked this, but I thought it was ooverkill to check everywhere. In any case, it's included here for didactic purposes.
CGPoint *points = malloc(sizeof(CGPoint) * mutableArrayOfPoints.count);
for (int i = 0; i < mutableArrayOfPoints.count; i++) {
points[i] = [mutableArrayOfPoints[i] pointValue];
}
The above is from memory. I haven't used malloc() in ages, so you may need to adjust syntax.

Find nearest float in array

How would I get the nearest float in my array to a float of my choice? Here is my array:
[1.20, 1.50, 1.75, 1.95, 2.10]
For example, if my float was 1.60, I would like to produce the float 1.50.
Any ideas? Thanks in advance!
You can do it by sorting the array and finding the nearest one.
For this you can use sortDescriptors and then your algorithm will go.
Even you can loop through, by assuming first as the required value and store the minimum absolute (abs()) difference, if next difference is lesser than hold that value.
The working sample, however you need to handle other conditions like two similar values or your value is just between two value like 2 lies between 1 and 3.
NSArray *array = #[#1.20, #1.50, #1.75, #1.95, #2.10];
double my = 1.7;
NSNumber *nearest = array[0];
double diff = fabs(my - [array[0] doubleValue]);
for (NSNumber *num in array) {
double d = [num doubleValue];
if (diff > fabs(my - d) ) {
nearest = num;
diff = my - d;
}
}
NSLog(#"%#", nearest);

Getting wrong distance between locations in iOS?

Hi aim using following method to find out the distance between my current location and the locations(lat and longitude) stored in NSMutableArray value.
But am getting wrong distance..Please help..
My code
-(void)getDistancetoShow:(NSMutableArray *)newArray{
CLLocationCoordinate2D coordinateUser = [self getLocation];
float _lat,_long;
first_Loc = [[CLLocation alloc] initWithLatitude:coordinateUser.latitude longitude:coordinateUser.longitude];
for(int p=0;p<[[newArray1 valueForKey:#"Name"] count];p++){
_lat=[[[newArray1 valueForKey:#"Latitude"] objectAtIndex:p]floatValue];
_long=[[[newArray1 valueForKey:#"Longitude"] objectAtIndex:p]floatValue];
second_loc=[[CLLocation alloc] initWithLatitude:_lat longitude:_long];
showDistance=[second_loc distanceFromLocation:first_Loc]/1000;
[distanceToDispaly addObject:[NSString stringWithFormat:#"%.2f KM",showDistance]];
}
NSLog(#"first=%#, second=%#", first_Loc, second_loc);
}
Latitudes in array
(
"47.0735010448824",
"47.0564688100431",
" 47.0582514311038",
"47.0587640538326",
"47.0569233603454",
"47.0541853132569",
"47.0542029215138",
"47.0544259594592",
"47.0560264547367",
" 47.0576532159776",
" 47.0550023679218",
"47.0342030007379",
"47.0746263896213",
" 47.0740256635512",
"47.0524765957921",
"47.0606287049051",
"47.0539691521825",
"47.0542799159057",
"47.0651001682846",
"47.0536948902097",
"47.0525973335309",
"47.0389265414812",
"47.0761811267051",
"47.0668801601942",
"47.0614859079241",
"47.0579433468181",
"47.0718998779465"
)
and longitude in array
(
"21.9154175327011",
"21.9312065669748",
"21.9337414545594",
" 21.9346772505188",
" 21.9300587945685",
"21.9363460105132",
"21.9362081709222",
"21.9343042603097",
"21.939485335992",
"21.9320057169724",
"21.9300799002643",
"21.9485373571669",
"21.9310667367526",
"21.9318507902135",
"21.9192195298473",
"21.9195273899529",
"21.9329595191441",
"21.9292015418841",
"21.9219452321208",
"21.9098849252041",
"21.9074768948561",
"21.9424499491422",
"21.9151458954504",
"21.9304346568769",
"21.9305973807911",
"21.9331511189507",
"21.9159872752442"
)
but the real distance in something like staring with 9**** but am getiing now 5***
CLLocation gives you crow(straight) distance between two places. I thinks you are getting crow distance.
First take coordinate of two places and find distance between them.
then search crow distance between those two coordinate.
hope this will help
Once you get the two coordinates you can calculate the distance between them using this piece of code (taken from here):
- (NSNumber*)calculateDistanceInMetersBetweenCoord:(CLLocationCoordinate2D)coord1 coord:(CLLocationCoordinate2D)coord2 {
NSInteger nRadius = 6371; // Earth's radius in Kilometers
double latDiff = (coord2.latitude - coord1.latitude) * (M_PI/180);
double lonDiff = (coord2.longitude - coord1.longitude) * (M_PI/180);
double lat1InRadians = coord1.latitude * (M_PI/180);
double lat2InRadians = coord2.latitude * (M_PI/180);
double nA = pow ( sin(latDiff/2), 2 ) + cos(lat1InRadians) * cos(lat2InRadians) * pow ( sin(lonDiff/2), 2 );
double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
double nD = nRadius * nC;
// convert to meters
return #(nD*1000);
}
Hope this helps!
To get distance from array of points in Swift use below reduce method.
Here locations is array of type CLLocation.
let calculatedDistance = locations.reduce((0, locations[0])) { ($0.0 + $0.1.distance(from: $1), $1)}.0

How to Create a Dynamic CGPoint** array

I have a few maps (tilemaps made with Tiled QT) and I would like to create a CGpoint **array based on the objects groups of those maps (I call them Waypoints).
Each maps can have a few set of waypoints that I call path.
//Create the first dimension
int nbrOfPaths = [[self.tileMap objectGroups] count];
CGPoint **pathArray = malloc(nbrOfPaths * sizeof(CGPoint *));
Then for the second dimension
//Create the second dimension
int pathCounter = 0;
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:#"Path%d", pathCounter]])) {
int nbrOfWpts = 0;
while ((waypoint = [path objectNamed:[NSString stringWithFormat:#"Wpt%d", nbrOfWpts]])) {
nbrOfWpts++;
}
pathArray[pathCounter] = malloc(nbrOfWpts * sizeof(CGPoint));
pathCounter++;
}
Now I want to fill up the pathArray
//Fill the array
pathCounter = 0;
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:#"Path%d", pathCounter]]))
{
int waypointCounter = 0;
//Get all the waypoints from the path
while ((waypoint = [path objectNamed:[NSString stringWithFormat:#"Wpt%d", waypointCounter]]))
{
pathArray[pathCounter][waypointCounter].x = [[waypoint valueForKey:#"x"] intValue];
pathArray[pathCounter][waypointCounter].y = [[waypoint valueForKey:#"y"] intValue];
NSLog(#"x : %f & y : %f",pathArray[pathCounter][waypointCounter].x,pathArray[pathCounter][waypointCounter].y);
waypointCounter++;
}
pathCounter++;
}
When I NSLog(#"%#",pathArray), it shows me the entire pathArray will the x and y.
HOWEVER 2 problems :
The y value is never correct (the x value is correct and my tilemap.tmx is correct too)
<object name="Wpt0" x="-18" y="304"/> <-- I get x : -18 and y :336 with NSLog
<object name="Wpt1" x="111" y="304"/> <-- I get x : 111 and y :336
<object name="Wpt2" x="112" y="207"/> <-- I get x : 112 and y :433
I get a EX_BAD_ACCESS at the end of the NSLog
EDIT
Thank you about the NSLog(%#) concerning CGPoint.
However, I get the y value with this line (in the ugly loop):
NSLog(#"x : %f & y : %f",pathArray[pathCounter][waypointCounter].x,pathArray[pathCounter][waypointCounter].y);
First of all, you can't NSLog CGPoint like that because it is not an object. %# expects an objective c object to send a description message to.
Secondly, you can use an NSValue wrapper and then use NSMutableArray as you would with any other object. Is there a reason you don't want to do that? You can add arrays inside other arrays as you are doing.
Regarding the first problem:
The y value is never correct (the x value is correct and my tilemap.tmx is correct too)
Have you noticed that if you add the y values from tile map and from NSLog they always add up to 640? Then you better check if tilemap y-coordinate is top-to-bottom as oppose to CGPoint's bottom-to-top. Then you can always do 640 - y to convert the y-coordinate between the two coordinate systems.

Resources