google fusion tables: finding nearest places (from the list in fusion table) from user current location (geolocation)

StackOverflow https://stackoverflow.com/questions/17461503

Question

I'm a newbie here and want to ask help on this problem. I've got a code that is supposed to mapped and list down the 5 nearest clinics to the user current location. This clinic is taken from the fusion table data that I have uploaded. This is the code that I have:

    function initialize() {

    var map = new google.maps.Map(document.getElementById('map-canvas'), {
      center: new google.maps.LatLng(3.148, 101.715),
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var layer = new google.maps.FusionTablesLayer({
        query: {
          select: 'Location',
          from: '16JfuLxarMf5UjxThG2Tno_SZoNSZ_ExwbQyCeu0',
          orderBy: 'ST_DISTANCE(Location, LATLNG(3.148, 101.715))',
          limit: 6
     }
   });
     layer.setMap(map);
  }

  google.maps.event.addDomListener(window, 'load', initialize);

The code that i have above works in mapping down the nearest clinic, but it depend on the coordinates. What i want is, for it to automatically detect the user current location and mapped and list down the clinic based from that.

I've got the code for the geolocation as below:

    window.onload = function() {
            if (navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(handle_geo); 
                    $("#queryInput").change(doSearch);
                } else {
                    var map = document.getElementById("map-canvas");
                    map.innerHTML = "Geolocation is not available... have you considered a forward-thinking browser?";
                }   
        };

However when i combine the code into this:

  window.onload = function() {
            if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(handle_geo); 
                    $("#queryInput").change(doSearch);
                } else {
                    var map = document.getElementById("map-canvas");
                    map.innerHTML = "Geolocation is not available... have you considered a forward-thinking browser?";
                }   
        };

        function handle_geo(position){ 
            // Initialize the map with default UI.
                gMap = new google.maps.Map(document.getElementById("map-canvas"), {
                center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
                zoom: 15,
                mapTypeId: 'roadmap'
            });

          var layer = new google.maps.FusionTablesLayer({
        query: {
          select: 'Location',
          from: '16JfuLxarMf5UjxThG2Tno_SZoNSZ_ExwbQyCeu0',
          orderBy: 'ST_DISTANCE(Location,'+map.getCenter().lat()+','+map.getCenter().lng()+'))',
          limit: 4
     }
   });
     layer.setMap(map);
  }

  google.maps.event.addDomListener(window, 'load', handle_geo);

It only manages to zoom into the user current location, but the nearest clinic is not mapped and listed. So how do i make this to work? thanks in advance.

Was it helpful?

Solution

In case the geolocation went right, you already have the variables lat, long available as the position.coords.latitude and position.coords.longitude, it's better to pass these variables on to the layer query. See working example here: https://plnkr.co/edit/sphxJn?p=preview ` function initialize(lat, long) { google.maps.visualRefresh = true; "use strict"; var map, layer; map = new google.maps.Map(document.getElementById("map-canvas"), { center: new google.maps.LatLng(lat, long), zoom: 10, mapTypeId: 'roadmap' });

    layer = new google.maps.FusionTablesLayer({
        query: {
          // Geotagged wikipedia articles, for test purpose
          // https://www.google.com/fusiontables/DataSource?docid=1LsJLUqlE_P2IYt4wFOHHi59fP_YWzdDoCKLlSPw
          select: 'Coordinates',
          from: '1LsJLUqlE_P2IYt4wFOHHi59fP_YWzdDoCKLlSPw',
          orderBy: 'ST_DISTANCE(Coordinates, LATLNG(' + lat + ',' + long + '))',
          //  Code for original table from SO-question below     
          //  select: 'Location',
          //  from: '16JfuLxarMf5UjxThG2Tno_SZoNSZ_ExwbQyCeu0',
          //  orderBy: 'ST_DISTANCE(Location, LATLNG(' + lat + ',' + long + '))',
          limit: 25
        }
      });
    layer.setMap(map);
  }

  function locate() {
    var lat, long;
    lat = 3.148,
    long = 101.715;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function success(position) {
        lat = position.coords.latitude;
        long = position.coords.longitude;
        initialize(lat, long);
      }, function (error) {
        switch (error.code) {
        case error.TIMEOUT:
          alert('Timeout. Try again.');
          return initialize(lat, long);
        case error.POSITION_UNAVAILABLE:
          alert('Your position is not available at the moment.');
          return initialize(lat, long);
        case error.PERMISSION_DENIED:
          alert('No geolocation. Things wont work out this way.');
          return initialize(lat, long);
        case error.UNKNOWN_ERROR:
          alert('Unknown error. Fyi.');
          return initialize(lat, long);
        }
      });
    } else {
      alert('Your device does not support geolocation');
      // IE-8 issue...
      return initialize(lat, long);
    }
  }`

Oh, and why your code didn't work out; you called both "handle_geo" (with google.maps.event.addDomListener(window, 'load', handle_geo);, and the first anonymous geolocation function: window.onload = function etc... at the same time (wth two different onload events) which messed things up. If you look at my example you will see that i call "locate" (function for getting the location) with an onload event on the last line, and "locate" then passing values retrieved from the location object as lat, long parameters and calls "initialize" (function for rendering the map with markers). Also, i've updated the query using the retrived lat, long variables (we have those already) instead of retrieving them with the function map.getCenter() Hope that this is of some more help to understand things. Ps As a bonus i've updated the code in the plnkr example with functions for a better error handling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top