Calculate Distance between points in fusion tables
Asked Answered
F

1

6

My programming knowledge is very limited and I'm working on a college project that includes programming.

What I want to do is a map, that shows your current location and the locations of recycling points. I already did the current location part, and I used the fusion tables to display the recycling points on the map. But I also wanted to give the option of finding the shortest route between your current location and the the recycling points.

So what it would do was to calculate the distance between your current location and every recycling point, and show the shortest one.

Right now I'm trying to understand google maps api tutorials and I don't know if this is possible, using the fusion tables. So I wanted to know if anyone knows how to do this.

Thank you so much!

<!DOCTYPE html>
<html>
<head>
<section id="wrapper">
Clique no botão "permitir" para deixar o browser encontrar a sua localização
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<article>
</article>
<script>


function success(position) {
  var mapcanvas = document.createElement('div');
  mapcanvas.id = 'mapcontainer';
  mapcanvas.style.height = '350px';
  mapcanvas.style.width = '450px';
  document.querySelector('article').appendChild(mapcanvas);

  var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

  var options = {
    zoom: 15,
    center: coords,
    mapTypeControl: false,
    navigationControlOptions: {
        style: google.maps.NavigationControlStyle.SMALL
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
  var marker = new google.maps.Marker({
      position: coords,
      map: map,
      title:"You are here!"
  });

  var layer = new google.maps.FusionTablesLayer({
    query: {
    select: 'Coordenadas',
    from: '1CwMDrcxebjsb8sjG42rbGVAZB25Zi7CvaLJXOCM'
  },


});
 layer.setMap(map)
}


if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success);
} else {
  error('Geo Location is not supported');
}
</script>
</section>

</head>
<body>

</body>

</html>
Fining answered 26/5, 2013 at 7:15 Comment(2)
How many "recycling points" are stored in the table?Lapse
Right now, there's only 15 but I'm not done adding points. I'm still waiting for information from a recycling company.Fining
D
6

UPDATE:

You may retrieve the nearest point coordinates by sending a query to Google Visualization API:

// Initiate the GViz query
var queryList = [];
queryList.push("SELECT Location FROM ");
queryList.push(tableId);
queryList.push(" ORDER BY ST_DISTANCE(Location, LATLNG(");
queryList.push(currentLat + "," + currentLng);
queryList.push(")) ");
queryList.push(" LIMIT 1");

var queryText = encodeURIComponent(queryList.join(''));
var query = new google.visualization.Query(
                         'http://www.google.com/fusiontables/gvizdata?tq=' +
                          queryText);

// Handling the result of nearest location query
query.send(function(response) {
    dataTable = response.getDataTable();

    // If there is any result
    if (dataTable && dataTable.getNumberOfRows()) {
        console.log("Nearest Point is: " + dataTable.getValue(0,0));

        // Result holds the coordinates of nearest point
        var result = dataTable.getValue(0,0).split(",");

        // Creates a Google Map LatLng from "result"
        var latlng = new google.maps.LatLng(result[0], result[1]);
        showRoute(latlng);
    }

});

You may check the live example Here.


You may use Distance Matrix Service for that purpose. You just read your origin from your current location and send a request to Distance Matrix Service for each recycling points. There is also an example at Distance Matrix Sample.

var mylocation = new google.maps.LatLng(CURRENT_LOCATION_LAT, CURRENT_LOCATION_LNG);

// Destination by address
var destination1 = "Stockholm, Sweden";

// or destination by lat and lng
var destination2 = new google.maps.LatLng(50.087692, 14.421150);

// Sending request
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [mylocation],
    destinations: [destination1, destination2],
    travelMode: google.maps.TravelMode.DRIVING, 
    avoidHighways: false,
    avoidTolls: false
  }, callback);

function callback(response, status) {
  // See Parsing the Results for
  // the basics of a callback function.
}

You can specify the Travel Mode which computes the duration accordingly.

google.maps.TravelMode.DRIVING (Default) indicates standard driving directions using the road network.
google.maps.TravelMode.BICYCLING requests bicycling directions via bicycle paths & preferred streets.
google.maps.TravelMode.TRANSIT requests directions via public transit routes. google.maps.TravelMode.WALKING requests walking directions via pedestrian paths & sidewalks.

Dowzall answered 26/5, 2013 at 9:46 Comment(10)
Hii. Thank you for your help (: Is there a way I can put my fusion tables points into the destinations?Fining
@JGuerreiro, Sorry I don't have access to my computer and I'm surfing SO with my phone which is really inconvenient. I'll reply you as soon as I get back.Dowzall
@JGuerreiro, I have updated my answer. Take a look and if you still need more explanation let me know.Dowzall
you have been really helpfull (: Can you help me with one more thing? Is there a way to know the coordinates of the nearest point? I would like to use the calcroute function to show the user the route between their current location and that point. Can I do that?Fining
@JGuerreiro, I have updated my answer again. Disregard my previous update and check the live version of the code at the same link. When the page is loaded, click anywhere on the map to see the nearest recycling point and the route from your location to it. Take a look at the source of the webpage for complete code.Dowzall
I already adapted your code to mine, but now I'm having trouble to incorporate my current location code into this one. The map stops showing. I don't know what to do :\Fining
@JGuerreiro, how do you get the current location? Edit your question and include your code.Dowzall
Ok, I did as you said and included the code I'm using for the current locationFining
@SamRad I'm attempting to do something very similar to this for a personal project and I'm stuck and just need some clarification on a few of your points. If you could possibly shoot me an email that'd be great! [email protected]Claptrap
@jamez14, what's the problem? You got the code on the link provided in my answer. If you have more questions, you better off asking them here in SO. You'll get a very quick answer. Believe me.Dowzall

© 2022 - 2024 — McMap. All rights reserved.