Search code examples
javascriptjquerygoogle-maps-api-3geolocationgoogle-fusion-tables

Return 3 closest locations to a users location (geolocation) and list those locations for them


Background:

I am working on a website/app built with HTML/CSS/Javascript that will use geolocation (Google Maps API) to find a users location (geolocation) and return them, for example, the top 5 closest water parks to them at that location they are currently at so they will be able to then navigate to one of those locations. I am using Google Fusion Tables to return the results to them.

Question:

I have been able to successfully...

  • Find the users location and put a marker there (using Map API/geolocation)
  • Return 3 out of 5 locations and put markers down for those 3 (I used Fusion Tables & limited results to 3)

I want to be able to…

  1. Return only the 3 closest locations to the user (i.e. calculate distance from users location to nearest water park)
  2. Put a "sidebar" or list of those 3 locations, detailing name, address, and other fields in my Fusion Table

I made a Fiddle below this code with what I have so far. The code below is my Fusion Table query, which I assume is what I will need to make the changes to in order to get the 3 closest locations (question #1). Question #2, listing those locations, might use all of the code I have in my Fiddle.

var base_query = {
    select: 'Location',
    from: '1MsmdOvWLKNNrtKnmoEf2djCc3Rp_gYmueN4FGnc',
    limit: 3
};

var ftLayer = new google.maps.FusionTablesLayer({
    map: map,
    query: $.extend({}, base_query)
});

var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < base_query.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(base_query[i][1], base_query[i][2]),
        map: map
    });

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent(base_query[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
};

var signChange = function () {
    var options = {
        query: $.extend({}, base_query)
    };
};

http://jsfiddle.net/jamez14/bRLaH/2/

Any help would be appreciated. I have been doing research on this question for some time, but for whatever reason I am not able to piece it all together. Any help/resources would be greatly appreciated!


Solution

  • Related to 1. (2. has been answered in the comments by geocodezip)

    Use a spatial_relationship in the orderBy-option of base_query.

    orderBy: 'ST_DISTANCE(Coordinates, LATLNG(lat,lng))
    

    ...where lat and lng has to be populated with the values returned by navigator.geolocation(what means that you must create the layer or at least set the query for the layer in the callback of navigator.geolocation.getCurrentPosition)