google maps api 3 route finder (distance of POI from route) - google-maps-api-3

I have the following code which is successfully plotting a route between two points. However I wish to search a recordset to see which georeferences lie within a range of this route. E.g. 50 yards off the main route
function plot_route() {
var rendererOptions = { map: map };
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var org = new google.maps.LatLng ( $("#start_lat").html(), $("#start_long").html() );
var dest = new google.maps.LatLng ( $("#finish_lat").html(), $("#finish_long").html() );
if ($("#via_lat").html() != "") {
var point1 = new google.maps.LatLng($("#via_lat").html(), $("#via_long").html());
}
else
{
point1 = dest;
}
var wps = [{ location: point1 }];
if (($("#start_lat").html() != "") && ($("#finish_lat").html() != "")) {
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
else
alert ('failed to get directions');
});
}
}
I have tried breaking down the response but it shows that the calculation does not return an array of values to make up the route.
Has anyone conquered this one before?
edit
Digging Deeper, it seems the response does contain the array of route points. For those in the community who are looking for help rather than contributions from people gung ho with the -1 button i attach the following
function plot_route() {
var rendererOptions = { map: map };
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var org = new google.maps.LatLng ( $("#start_lat").html(), $("#start_long").html() );
var dest = new google.maps.LatLng ( $("#finish_lat").html(), $("#finish_long").html() );
if ($("#via_lat").html() != "") {
var point1 = new google.maps.LatLng($("#via_lat").html(), $("#via_long").html());
}
else
{
point1 = dest;
}
var wps = [{ location: point1 }];
if (($("#start_lat").html() != "") && ($("#finish_lat").html() != "")) {
var request = {
origin: org,
destination: dest,
waypoints: wps,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myroute = response.routes[0];
if(myroute)
{
$.each(myroute, function(key, value) {
if (key == "overview_path") {
alert(value); //the array of points for the route
}
});
}
directionsDisplay.setDirections(response);
}
else
alert ('failed to get directions');
});
}
}

Related

Google Places API returning ZERO_RESULTS for some places only

For some places like airports or train stations my code is working fine, it also works fine when entering a complete address like "16 Cours du Médoc, Bordeaux, France", but for most places it doesn't work and I get the ZERO_RESULTS status.
I am totally confused and can't find where the problem is.
Here is the code :
var drop = document.getElementById('destination');
var drop_autocomplete = new google.maps.places.Autocomplete(drop);
drop_autocomplete.bindTo('bounds', map);
drop_autocomplete.addListener('place_changed', function() {
var placea = drop_autocomplete.getPlace();
nom_arrivee = placea.name;
arrivee_formulaire = placea.formatted_address;
vicina = placea.vicinity;
latitudeArrivee = placea.geometry.location.lat();
longitudeArrivee = placea.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function doCalculation()
{
var cartypes=document.getElementById('cartypes').value;
var address = document.getElementById('source').value;
var destination = document.getElementById('destination').value;
if(cartypes.trim()=='')
{
alert("Please Select Car Type. if Cartype is empty, then you need to inser first from admin side.");
return false;
}
if(address.trim() == '') {
alert("Please Enter Pickup Address");
source = '';
return false;
}
if(destination.trim() == '') {
alert("Please Enter Drop Off Address");
destination = '';
return false;
}
if (first_time)
{
jQuery("#map_canvas").show(600);
setTimeout(sourceAddress, 800);
first_time = false;
} else {
sourceAddress();
}
}
function sourceAddress() {
clear();
jQuery("#map_canvas").show(800);
waypoints = new Array();
var address = document.getElementById('source').value;
var destination = document.getElementById('destination').value;
geocoder.geocode({'address': address}, function(results, status) {
console.log(results);
if (status == google.maps.GeocoderStatus.OK) {
var lat = document.getElementById("latitude").value = results[0].geometry.location.lat();
var lng = document.getElementById("longitude").value = results[0].geometry.location.lng();
var lng = document.getElementById("dest_latitude").value = results[0].geometry.location.lng();
var lng = document.getElementById("dest_longitude").value = results[0].geometry.location.lng();
var marker = new google.maps.Marker({
map: map,
icon: home,
position: results[0].geometry.location
});
markers[count_markers++] = marker;
destinationAddress();
}
else {
alert('Result was not successful for the following reason: ' + status);
}
});
}
function destinationAddress() {
var source = document.getElementById('source').value;
var address = document.getElementById('destination').value;
var request = {
origin: source,
destination: address,
waypoints: waypoints,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = document.getElementById("dest_latitude").value = results[0].geometry.location.lat();
var lng = document.getElementById("dest_longitude").value = results[0].geometry.location.lng();
var marker = new google.maps.Marker({
map: map,
icon: taxi,
position: results[0].geometry.location
});
markers[count_markers] = marker;
var picLatLng = new google.maps.LatLng(jQuery('#latitude').val(), jQuery('#longitude').val());
var dropLatLng = new google.maps.LatLng(jQuery('#dest_latitude').val(), jQuery('#dest_longitude').val());
markerBounds.extend(picLatLng);
markerBounds.extend(dropLatLng);
map.fitBounds(markerBounds);
calc();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

Can't get Google Maps api v3 to display markers from xml file

I should have on my hands what is proper working JS and an xml file...I'm simply trying to take advantage of the huge database of locations that has been offered up as free for everyone to use - located # http://www.craftbeer.com/breweries/brewery-locator/find-a-us-brewery
I'm tried using their maps.js and xml file...but all I end up with is a blank maps screen...
Here is the Javascript...
/*********************************************
**Google Maps Custom API work**
This code can be reused on any site to display a local map of breweries from our local iMis dump, as well as pull in beermapping.
Hey! Don't forget to include API in functions.php! Function is conditionally initialized in footer.php
*/
//Set up variables to create marker
var gmarkers = [];
var mapMarkers = [];
var geocoder = new google.maps.Geocoder();
var icon = 'http://www.craftbeer.com/wp-content/uploads/marker.png';
//Initialize Map
function view_map(xml_file, latitude, longitude, varZoom) {
console.log('view map');
map = new google.maps.Map(document.getElementById("map_canvas"), { //Create the map, Set Default Zoom level and type
center: new google.maps.LatLng(latitude, longitude),
zoom: varZoom,
mapTypeId: 'roadmap',
panControl: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
overviewMapControl: false
});
//-- Listeners --//
google.maps.event.addListener(map, 'center_changed', function() {
console.log('center changed');
//clearMarkers();
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
console.log("loaded");
$("#loading-screen").fadeOut(250, function(){});
$("#loading-icon").fadeOut();
//google.maps.event.addListenerOnce(map, 'tilesloaded', function(){ });
});
//console.log(xml_file);
var download_file = xml_file; //this variable is passed in so we can re-use this script
//Pull in the XML feed
downloadUrl(download_file, function(data) {
console.log("downloading xml");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//Loop through all markers in the XML file
for (var i = 0; i < markers.length; i++) {
var state = markers[i].getAttribute("state");
var x = markers[i].getAttribute("lat");
var y = markers[i].getAttribute("lng");
if ( state != 'PR' && state != 'VI' && state != 'GU' && x != "" ){
//console.log(state);
var ids = parseFloat(markers[i].getAttribute("id"));
var z = new google.maps.LatLng(x,y,i);
//console.log(x);
var _id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var city = markers[i].getAttribute("city");
var zip = markers[i].getAttribute("zip");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var brewery_type = markers[i].getAttribute("type");
var member_type = '';
var member_type = markers[i].getAttribute("member_type");
var offer = markers[i].getAttribute("offer");
var html = "<div class='bubble_content'><strong>" + name + "</strong><br />";
html += address + "<br/>" + city + ", " + state + " " + zip;
if(url) html += "<br /><br /><a href='http://" + url + "' target='_blank'>Visit Web Site</a></div>";
//var marker = createMarker(ids, z, title, contentstring);
var marker = new google.maps.Marker({
position: z,
map: map,
title: name,
icon: icon,
html: html,
zindex: i
});
//Add a listener for every icon click
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,this);
//map.setZoom(10);
//map.setCenter(this.getPosition());
console.log(this);
});
gmarkers[ids] = marker;
mapMarkers.push(marker);
if( x && y ){
//console.log(ids);
var infowindow = new google.maps.InfoWindow({content: html});
}
/* google.maps.event.addListener(marker, 'click', function() {
console.log('marker clicked');
});
*/
//bounds.extend(z);
//map.fitBounds(bounds);
}//end check for US states only!
} //end for loop
var mcOptions = {gridSize: 60, maxZoom: 9};
var markerCluster = new MarkerClusterer(map, mapMarkers, mcOptions); //this is the function that groups the icons into markers
});
} //End full function to create map
/*
* FUNCTION
*
* click to bring up one icon when clicked from the list.
*/
function myclick(i){
console.log('clicked a title ' + i);
smoothScroll("#primary");
var lat = parseFloat(gmarkers[i].position.k);
var lng = parseFloat(gmarkers[i].position.B);
console.log(lat);
map.setCenter({lat: lat, lng: lng});
map.setZoom(13);
google.maps.event.trigger(gmarkers[i], 'click');
};
function createMarker(ids, z, title, contentstring){
console.log('createMarker');
var marker = new google.maps.Marker({
position: z,
map: map,
title: title,
html: contentstring,
icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png'
});
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(this.html);
infowindow.open(map,marker);
});
gmarkers[ids] = marker;
//console.log(gmarkers[ids]);
};
/*
* FUNCTION findAddress()
*
* given an adress string, zoom the map to the proper state
*/
function findAddress(position) {
//Let's determind if we have a state (address) or LatLng
var addressStr = $("#state_select li.active").data('state-id');
if (addressStr != 'Select a State') address = "US State of "+addressStr;
if(position) {
var lat = parseFloat(position['latitude']);
var lng = parseFloat(position['longitude']);
var latlng = new google.maps.LatLng(lat, lng);
//console.log(latlng);
}
//Now let's geocode - two different cases
if (geocoder && position) { //If LatLng
//console.log('near me');
geocoder.geocode( { 'location': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(13);
}
} else {
alert("No results found");
}
}
});
} else if (geocoder && address!="") { //If State
//console.log('by state');
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport && addressStr!="ON" && addressStr!="INT") {
map.fitBounds(results[0].geometry.viewport); //resize map to fit.
map.setZoom(6);
}
} else {
alert("No results found");
}
}
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
And here is the link to the xml file....
http://www.straighttothepint.com/wp-content/uploads/wp-google-maps/Google_Map_APIs.xml
I've spent days doing google searches and testing different sections of code to at least get a basic google map to show up via the xml file markers...but to no avail - Any help would be tremendously appreciated!!
~Cheers
EDIT:
Everything worked as expected once I included the following script inline on the page prior to calling the maps.js file. Thanks everyone!
<script>
$(document).ready(function(){
var latitude = 39.300299;
var longitude = -97.382812;
view_map('./uploads/your_xml_file.xml', latitude,longitude,4);
//scripts to handle mapping are in js/mylibs/map.js.php
});
</script>
Looking at the html and the code you provided above I constructed a fiddle for you:
http://jsfiddle.net/loanburger/qafsex5x/
I added two markers in an xml string at the top in the fiddle.
I basically parse the xml doing this:
var markers = $(xml).find("marker");
Its then simply the same for loop you had:
for (var i = 0; i < markers.length; i++)
{
...
}
The fiddle will show you the markers.

Google maps API v3 initialize function

I'd like to lean up my initialize() function... but every time I do, it breaks my code.
I'm eventually trying to do something like this, where I have a sidebar with stuff that's directly related to the markers on the map, AJAX'd in... Firstly, I'd like to be able to put other functions outside of the initialize() function. This works fine:
<script>
function initialize() {
// create the map object
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
// create your location marker
var mylocOptions = {
draggable: true,
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22,22),
new google.maps.Point(0,18),
new google.maps.Point(11,11)),
title: "You are here..."
};
var myloc = new google.maps.Marker(mylocOptions);
// get location information from browser, or from user input, or from database
<% if !signed_in? || !current_user.loc %>
if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
$.ajax({
data: { me: me.toString() },
type: 'POST',
url: '/set-location'
})
}, function(error) {
var address = prompt('Where are you looking?');
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var me = results[0].geometry.location
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
} else {
alert("Geocode was not successful for the following reason: " + status);
};
});
});
<% else %>
var me = new google.maps.LatLng(<%= current_user.loc %>);
myloc.setPosition(me);
myloc.setMap(map);
map.setCenter(me);
map.setZoom(12);
<% end %>
// watch for marker movement, and update location accordingly
var oldPos = myloc.getPosition();
google.maps.event.addListener(myloc, "dragend", function(e){
revGeo = new google.maps.Geocoder();
var newPos = myloc.getPosition();
$.ajax({
data: { me: newPos.toString() },
type: 'GET',
url: '/set-location'
})
if(oldPos != newPos)
revGeo.geocode({'latLng': newPos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#loc').html(results[1].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
oldPos = newPos;
});
// when creating an event, check for event location,
// verify it's existance and put a marker down on the map
$(document).on('focusout', '#event_location', function() {
geocoder = new google.maps.Geocoder();
address = document.getElementById("event_location").value;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var coords = results[0].geometry.location;
map.setCenter(coords);
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: coords
});
$('#coords').html('coordinates: ' + coords)
$('#event_geocode').val(coords.toString())
} else {
alert(status + " for " + address);
};
});
});
}
</script>
... but I'm sure it can be broken up. Any ideas of what I'm doing wrong?

hiding the last direction marker with Google maps api

I've calculated a route with the same begin and end point with the maps api.
Because the begin and end point are the same, the first marker is overlapped by the last marker. Now I want only the last marker removed.
I only know how to hide them all with:
directionsDisplay.suppressMarkers = true;
Is there a way to loop through the markers and remove the last one?
this is the code I use for the directions:
function calcRoute(waypts) {
var start = waypts[0].location;
var end = waypts[0].location;
var request = {
origin:start,
destination:end,
waypoints:waypts,
optimizeWaypoints: true,
provideRouteAlternatives:false,
travelMode:google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.suppressInfoWindows = true;
directionsDisplay.suppressMarkers = true;
directionsDisplay.setDirections(response);
console.log(status);
}else{
alert('SATUS:'+response.status);
}
});
}
Try this
In initialise
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
then
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
var start =route.legs[0].start_location;
var end =route.legs[0].end_location;
addMarker(end);
addMarker function
function addMarker(pos){
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: 'images/your image'
}
)
}
I have not tested this but you should get the idea

distance matrix google maps javascript api3

I play with distance matrix
http://code.google.com/apis/maps/documentation/javascript/services.html#distance_matrix
to get the duration from one origin to multiple destinations.
I have this code:
var duration = new Array();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destination,
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
function(response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
for (var j = 0; j < results.length; j++)
duration[j] = results[j].duration.value;
}
});
alert(duration[0]);
but i have alert "undefined". when i put the alert command inside the callback function i have the alert i want. why is that??? how can i fix it?
Thank u in advance!
var duration = new Array();
function calculate_distance(){
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: destination,
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
function(response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
for (var j = 0; j < results.length; j++)
duration[j] = results[j].duration.value;
}
});
}
google.maps.event.addListener(autocomplete, 'place_changed', calculate_distance);
alert(duration[0]);
Try anything like that
Move the alert in to the callback. The function is a callback that is executed asynchronously.

Resources