EzDevInfo.com

geo

Small, fast & simple JavaScript mapping and geo API as a jQuery plugin

Querying within longitude and latitude in MySQL

Before asking for specific code examples, I just wanted to ask whether it is possible to make a query something like this pseudo code:

select items from table where lat/lon = -within x miles of a certain lat/lon point-

Is that doable? Or do I have to jump through some hoops? Any good approaches that could be recommended would be great!


Source: (StackOverflow)

How to read external GeoJSON file from openlayers?

I have to draw some lines by OpenLayers. The line features are coded as GeoJSON format. My code is ok for hard coded GeoJSON features. But, if I put this features in separate file and try to load it. It just does not work. I do not know what is the wrong with my loading external GeoJSON file. I have given both the code.

Code 1:

// This code is ok with hard coded GeoJSON features
map.addControl(new OpenLayers.Control.LayerSwitcher());

            vectorLayer = new OpenLayers.Layer.Vector("Lines");

            var myGeoJSON = { "type": "FeatureCollection",
                "features": 
                [

                    { "type": "Feature", "properties": { "LENGTH": 756.304000}, "geometry": { "type": "LineString", "coordinates": [ [ 18.105018, 59.231027 ], [ 18.104176, 59.230737 ], [ 18.103928, 59.230415 ], [ 18.103650, 59.230336 ], [ 18.103028, 59.230463 ], [ 18.102491, 59.230418 ], [ 18.101976, 59.230237 ], [ 18.100893, 59.230110 ], [ 18.100117, 59.230016 ], [ 18.097715, 59.230262 ], [ 18.096907, 59.230376 ], [ 18.096637, 59.230405 ], [ 18.096578, 59.230428 ], [ 18.096429, 59.230450 ], [ 18.096336, 59.230479 ], [ 18.096108, 59.230534 ], [ 18.095971, 59.230600 ], [ 18.095925, 59.230633 ], [ 18.095891, 59.230665 ], [ 18.094000, 59.231676 ], [ 18.093864, 59.231720 ] ] } }
                    ,                   
            { "type": "Feature", "properties": { "LENGTH": 1462.390000}, "geometry": { "type": "LineString", "coordinates": [ [ 17.877073, 59.461653 ], [ 17.877116, 59.461598 ], [ 17.876936, 59.461507 ], [ 17.876936, 59.461323 ], [ 17.876773, 59.461098 ], [ 17.876430, 59.460885 ], [ 17.876413, 59.460553 ], [ 17.876576, 59.460280 ], [ 17.876575, 59.460078 ], [ 17.876762, 59.460060 ], [ 17.877371, 59.460042 ], [ 17.877808, 59.460046 ], [ 17.878641, 59.460046 ], [ 17.879010, 59.460078 ], [ 17.879337, 59.460044 ], [ 17.879526, 59.459878 ], [ 17.879749, 59.459563 ], [ 17.880058, 59.459538 ], [ 17.880435, 59.459503 ], [ 17.887550, 59.453608 ], [ 17.887696, 59.453430 ], [ 17.887971, 59.453150 ], [ 17.888221, 59.452843 ], [ 17.888246, 59.452721 ], [ 17.888435, 59.452609 ], [ 17.888470, 59.452568 ], [ 17.888517, 59.452410 ] ] } }

                ]
            };

            var geojson_format = new OpenLayers.Format.GeoJSON({
                'internalProjection': map.baseLayer.projection,
                'externalProjection': new OpenLayers.Projection("EPSG:4326")
            });


            map.addLayer(vectorLayer);

            vectorLayer.addFeatures(geojson_format.read(myGeoJSON));

            map.setCenter(
                new OpenLayers.LonLat(18.068611, 59.329444).transform(
                    new OpenLayers.Projection("EPSG:4326"),
                    map.getProjectionObject()
                ), 10
            );

Code 2: This code shows an error that it could not load features

//This code does not work because it can not load the external GeoJSON file

map.addControl(new OpenLayers.Control.LayerSwitcher());

vectorLayer = new OpenLayers.Layer.Vector("Lines");

var myGeoJSON = new OpenLayers.Layer.Vector("Lines", {
    strategies: [new OpenLayers.Strategy.Fixed()],                
    protocol: new OpenLayers.Protocol.HTTP({
           url: "ml/lines.json"

           })
     });

var geojson_format = new OpenLayers.Format.GeoJSON({
    'internalProjection': map.baseLayer.projection,
    'externalProjection': new OpenLayers.Projection("EPSG:4326")
    });

map.addLayer(vectorLayer);

vectorLayer.addFeatures(geojson_format.read(myGeoJSON));

map.setCenter(
     new OpenLayers.LonLat(18.068611, 59.329444).transform(
         new OpenLayers.Projection("EPSG:4326"),
             map.getProjectionObject()
                ), 10
            );

Thanks in advance


Source: (StackOverflow)

Advertisements

Get nearest places on Google Maps, using MySQL spatial data

I have a database with a list of stores with latitudes and longitudes of each. So based on the current (lat, lng) location that I input, I would like to get a list of items from those within some radius like 1 km, 5km etc?

What should be the algorithm? I need the PHP code for algorithm itself.


Source: (StackOverflow)

Calculate the center point of multiple latitude/longitude coordinate pairs

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all points)?

EDIT: Python solution I've used:

Convert lat/lon (must be in radians) to Cartesian coordinates for each location.
X = cos(lat) * cos(lon)
Y = cos(lat) * sin(lon)
Z = sin(lat)

Compute average x, y and z coordinates.
x = (x1 + x2 + ... + xn) / n
y = (y1 + y2 + ... + yn) / n
z = (z1 + z2 + ... + zn) / n

Convert average x, y, z coordinate to latitude and longitude.
Lon = atan2(y, x)
Hyp = sqrt(x * x + y * y)
Lat = atan2(z, hyp)

Source: (StackOverflow)

Formulas to Calculate Geo Proximity

I need to implement a Geo proximity search in my application but I'm very confused regarding the correct formula to use. After some searches in the Web and in StackOverflow I found that the solutions are:

  1. Use the Haversine Formula
  2. Use the Great-Circle Distance Formula
  3. Use a Spatial Search Engine in the Database

Option #3 is really not an option for me ATM. Now I'm a little confused since I always though that the Great-Circle Distance Formula and Haversine Formula were synonymous but apparently I was wrong?

Haversine Formula

The above screen shot was taken from the awesome Geo (proximity) Search with MySQL paper, and uses the following functions:

ASIN, SQRT, POWER, SIN, PI, COS

I've also seen variations from the same formula (Spherical Law of Cosines), like this one:

(3956 * ACOS(COS(RADIANS(o_lat)) * COS(RADIANS(d_lat)) * COS(RADIANS(d_lon) - RADIANS(o_lon)) + SIN(RADIANS(o_lat)) * SIN(RADIANS(d_lat))))

That uses the following functions:

ACOS, COS, RADIANS, SIN

I am not a math expert, but are these formulas the same? I've come across some more variations, and formulas (such as the Spherical Law of Cosines and the Vincenty's formulae - which seems to be the most accurate) and that makes me even more confused...

I need to choose a good general purpose formula to implement in PHP / MySQL. Can anyone explain me the differences between the formulas I mentioned above?

  • Which one is the fastest to compute?
  • Which one provides the most accurate results?
  • Which one is the best in terms of speed / accuracy of results?

I appreciate your insight on these questions.


Based on theonlytheory answer I tested the following Great-Circle Distance Formulas:

  • Vincenty Formula
  • Haversine Formula
  • Spherical Law of Cosines

The Vincenty Formula is dead slow, however it's pretty accurate (down to 0.5 mm).

The Haversine Formula is way faster than the Vincenty Formula, I was able to run 1 million calculations in about 6 seconds which is pretty much acceptable for my needs.

The Spherical Law of Cosines Formula revealed to be almost twice as fast as the Haversine Formula, and the precision difference is neglectfulness for most usage cases.


Here are some test locations:

  • Google HQ (37.422045, -122.084347)
  • San Francisco, CA (37.77493, -122.419416)
  • Eiffel Tower, France (48.8582, 2.294407)
  • Opera House, Sydney (-33.856553, 151.214696)

Google HQ - San Francisco, CA:

  • Vincenty Formula: 49 087.066 meters
  • Haversine Formula: 49 103.006 meters
  • Spherical Law of Cosines: 49 103.006 meters

Google HQ - Eiffel Tower, France:

  • Vincenty Formula: 8 989 724.399 meters
  • Haversine Formula: 8 967 042.917 meters
  • Spherical Law of Cosines: 8 967 042.917 meters

Google HQ - Opera House, Sydney:

  • Vincenty Formula: 11 939 773.640 meters
  • Haversine Formula: 11 952 717.240 meters
  • Spherical Law of Cosines: 11 952 717.240 meters

As you can see there is no noticeable difference between the Haversine Formula and the Spherical Law of Cosines, however both have distance offsets as high as 22 kilometers compared to the Vincenty Formula because it uses an ellipsoidal approximation of the earth instead of a spherical one.


Source: (StackOverflow)

How to convert latitude or longitude to meters?

If I have a latitude or longitude reading in standard NMEA format is there an easy way / formula to convert that reading to meters, which I can then implement in Java (J9)?

Edit: Ok seems what I want to do is not possible easily, however what I really want to do is:

Say I have a lat and long of a way point and a lat and long of a user is there an easy way to compare them to decide when to tell the user they are within a reasonably close distance of the way point? I realise reasonable is subject but is this easily do-able or still overly maths-y?


Source: (StackOverflow)

Given the lat/long coordinates, how can we find out the city/country?

For example if we have these set of coordinates

"latitude": 48.858844300000001,
"longitude": 2.2943506,

How can we find out the city/country?


Source: (StackOverflow)

Android GEO Location Tutorial [closed]

Does anyone know a good GEO Location tutorial for Android. I don’t want to have to get a Google maps API key I just want an Activity that gets the location of a phone and sticks it in a variable that I can then decide what to do with it later.

Cheers,

Mike.


Source: (StackOverflow)

How can i calculate the distance between two gps points in Java?

I used this code but it doesnt work:

Need the distance between two gps coordinates like 41.1212, 11.2323 in kilometers (Java)

double d2r = (180 / Math.PI);
double distance = 0;

try{
    double dlong = (endpoint.getLon() - startpoint.getLon()) * d2r;
    double dlat = (endpoint.getLat() - startpoint.getLat()) * d2r;
    double a =
        Math.pow(Math.sin(dlat / 2.0), 2)
            + Math.cos(startpoint.getLat() * d2r)
            * Math.cos(endpoint.getLat() * d2r)
            * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 6367 * c;

    return d;

} catch(Exception e){
    e.printStackTrace();
}

Source: (StackOverflow)

How to define object in array in Mongoose schema correctly with 2d geo index

I'm currently having problems in creating a schema for the document below. The response from the server always returns the "trk" field values as [Object]. Somehow I have no idea how this should work, as I tried at least all approaches which made sense to me ;-)

If this helps, my Mongoose version is 3.6.20 and MongoDB 2.4.7 And before I forget, it would be nice to also set it as Index (2d)

Original data:

{
    "_id": ObjectId("51ec4ac3eb7f7c701b000000"),
    "gpx": {
        "metadata": {
            "desc": "Nürburgring VLN-Variante",
            "country": "de",
            "isActive": true
        },
    "trk": [
    {
        "lat": 50.3299594,
        "lng": 6.9393006
    },
    {
        "lat": 50.3295046,
        "lng": 6.9390688
    },
    {
        "lat": 50.3293714,
        "lng": 6.9389939
    },
    {
        "lat": 50.3293284,
        "lng": 6.9389634
    }]
    }
}

Mongoose Schema:

var TrackSchema = Schema({
            _id: Schema.ObjectId,
            gpx: {
                metadata: {
                    desc: String,
                    country: String,
                    isActive: Boolean
                },
                trk: [{lat:Number, lng:Number}]
            }
        }, { collection: "tracks" });

The response from the Network tab in Chrome always looks like this (that's only the trk-part which is wrong) :

{ trk: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],

I already tried different Schema definitions for "trk":

  1. trk: Schema.Types.Mixed
  2. trk: [Schema.Types.Mixed]
  3. trk:[ { type:[Number], index: "2d" }]

Hope you can help me ;-)


Source: (StackOverflow)

What is the proper way to use D3's projection.stream()?

So I'm experimenting a bit with D3's geo stream API, and things feel a bit hazy. I've been reading through the documentation here:

https://github.com/mbostock/d3/wiki/Geo-Streams

One point of confusion I have is the proper implementation of stream transforms. Let's say I create one:

//a stream transform that applies a simple translate [20,5]:
var transform = d3.geo.transform({
    point:function(){this.stream.point(x+20,y+5)}
}) 

Per the documentation, this.stream references the "wrapped stream." But what is the stream, really? From what I can gather, it is more of a procedure than explicit data structure--a sequence of data and function calls to transform the data. The syntax above seems to suggest that the wrapped stream is simply the object containing "stream listeners"

Moving on, I'm able to apply the stream transform using the projection method:

//a path generator with the transform applied using the projection() method
var path = d3.geo.path().projection(transform);

While I don't quite understand the underlying mechanics, the effect seems relatively straightforward: the underlying transform function of the path generator is called with transformed x,y arguments.

For my use case, I don't find this that helpful, particularly because my input data is not already projected. I'd like to use a projection to transform the data first, then transform those outputted coordinates. To that end, is there a general pattern for layering transforms?

I see that D3 does provide the projection.stream(listener) pattern which applies the projecting transform first, before applying the listener, but I'm not sure how to implement this. What should the listener argument be? Here's an example: http://jsfiddle.net/kv7yn8rw/2/.

Any guidance would be greatly appreciated!


Source: (StackOverflow)

How to use Redis and geo proximity search to find two users at the same location?

I want to implement a service that, given users' geo coordinates, can detect whether two users are at the very same location in real time.

In order to do this in real time and to scale, it seems I should go with a distributed in-memory datastore like Redis. I have researched using geohashing, but the problem is that points close to each other may not always share the same hash prefix. And geohashing may be overkill since I'm interested in finding whether two users are close enough where they are standing next to each other.

The simple solution of course is just to test whether pairs of geo coordinates fall within a small distance of each other. But AFAIK, Redis and other in-memory datastorse don't have geospatial indexing to support that kind of look-up.

What is the best way to go about implementing this?


Source: (StackOverflow)

How to perform bilinear interpolation in Python

I would like to perform blinear interpolation using python.
Example gps point for which I want to interpolate height is:

B = 54.4786674627
L = 17.0470721369

using four adjacent points with known coordinates and height values:

n = [(54.5, 17.041667, 31.993), (54.5, 17.083333, 31.911), (54.458333, 17.041667, 31.945), (54.458333, 17.083333, 31.866)]


z01    z11

     z
z00    z10


and here's my primitive attempt:

import math
z00 = n[0][2]
z01 = n[1][2]
z10 = n[2][2]
z11 = n[3][2]
c = 0.016667 #grid spacing
x0 = 56 #latitude of origin of grid
y0 = 13 #longitude of origin of grid
i = math.floor((L-y0)/c)
j = math.floor((B-x0)/c)
t = (B - x0)/c - j
z0 = (1-t)*z00 + t*z10
z1 = (1-t)*z01 + t*z11
s = (L-y0)/c - i
z = (1-s)*z0 + s*z1


where z0 and z1

z01  z0  z11

     z
z00  z1   z10


I get 31.964 but from other software I get 31.961.
Is my script correct?
Can You provide another approach?


Source: (StackOverflow)

What measurement unit is used to determine GPS accuracy with the HTML5 geo API?

I use HTML5's geolocation API and the position object has a "accuracy" property which is a number that may vary depending on the accuracy of the positioning.

So far so good. But the value is an unspecified unit.. sometimes it's 60, or 1250 or even 18 000.

I've read the W3C Geolocation API Specification[1], they talk about this property but never mention how it should be interpreted.

The only place I've found a possible answer is in the Department of Defence World Geodic System[2] technical report.. They mention accuracy in cm units with a 1σ (standard deviation).

But that doesn't tell me what's the accuracy unit that the HTML5 geolocation API returns me.. I can only suppose it's in cm..

[1] http://dev.w3.org/geo/api/spec-source.html

[2] http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf


Source: (StackOverflow)

Understanding if a CLLocation represents land or ocean

I am trying to build an API that would allow understanding whether or not a CLLocation represents land or not. I need this to work offline as I expect most of my users not to have connectivity. I'm using MapBox as a tile server but this is still a MapKit question because I'm not using the MapBox SDK.

I've tried several approaches to figuring out if a given coordinate represents a land or ocean location:

  • Offline database of coordinates that roughly make up the world's coastline. Still a problem to figure out whether or not a given point is inside or outside the contour.
  • Color analysis of a png tile resource (there MUST be a better way! Also requires a lot of offline data to be available in order to be an effective approach)

Also (after the above is dealt with) is there an effective way to decide given a tile coordinate (x,y,z) whether or not it's a land/sea/coast tile?

If anyone has ever struggled with this issue, I'd appreciate some advise here.


Source: (StackOverflow)