different results between map.google.com and google api for javascript - google-maps

i'm making simple website that helps to find direction between 2 points.
and i found something strange.
if i search through map.google.com it returns exact results, but mine dose not.
for example, i set "New York University, New York, NY, United States" as origin and "260 Broadway New York NY 10007" as destination using map.google.com
using map.google.com
if i use my website using googleMap API->
using api
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDs8SYxRh-pMXa9Qe-K1nVY0g3CLpmJ9mo&signed_in=true&libraries=places&callback=initMap" async defer></script>
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
directionsDisplay.setPanel(document.getElementById('panel'));
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: document.getElementById('pac-input').value,
destination: document.getElementById('pac-input2').value,
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
//showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}

It looks like you have places autocomplete inputs and read value of these inputs in your code.
I can suggest using the place ID from places autocomplete in your directions service. This way you will be sure that you work with the address that was chosen.
Look at this example and type there your addresses http://jsbin.com/xuyisem/1/edit?html,output

Related

Multiple directions on the same Google Map on click

I would like to reproduce a multi direction route sistem on the same Google Map like this website: http://hotelberna.com/en/where-we-are/
The same start point and multiple destinations. When I click on each final destination, then the map show me the new route.
Thanks in advance
I think you must be talking about something like this, right?
http://jsfiddle.net/dm1o1ktf/
(a modified version of the sample code in the documentation)
What you need is to trigger some function like calcRoute when you select a new location; in which you calculate the new route using the directionsService, like this:
function calcRoute() {
var start = "Mountain View, CA";
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}

Plotting more than 8 waypoints in Google Maps v3

Migrating code from Javascript API 2 to 3. I have a list of locations which i need to plot in the form of a driving directions. This was done in v2 using the following code
directions = new GDirections(map);
directions.loadFromWaypoints(waypoints, {preserveViewport: true});
Here is my attempt at converting this to V3
var request = {
origin: startLoc,
destination: endLoc,
waypoints: waypoints,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
Not the whole code, but the general idea. Seems to work fine, with one little issue. When there are more than 8 waypoints, the call fails. This is expected since Google Maps API v3 Docs states
The maximum allowed waypoints is 8, plus the origin, and destination. Maps API for Business customers are allowed 23 waypoints, plus the origin, and destination. Waypoints are not supported for transit directions.
Since i didn't run in to this issue in v2, is this a new restriction with v3? I wonder if i am using something that was not designed for what i need. This is a very lightly used applicaton with 2 users, so i am not sure if an expensive business license is worth the return. Emails to Google maps team have not yet been returned. Any workarounds/pointers will be of great help. Thanks.
One possible work around (particularly for a lightly used site) is to use multiple DirectionsService requests.
example 1 (addresses)
example 2 (coordinates)
Use Should need to Use array concept like these...
directionsService[i].route({
'origin': start,
'destination': end
'waypoints': waypts,
'travelMode': 'DRIVING'
},
function (directions, status){
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay[j].setDirections(directions);
}
});
in these directionservice and directiondisplay are should be in array logic
and using looping concepts use should need to assign start,end and waypoints dynamically and
try sending multiple request means u ll get the route for n number of latlon's ...but the markers ll be repeat with same name after 8 waypoints for that we remove the default markers by using supressmarkers false property...
As others said, it's imposable to do it using Google's JavaScript API. However, Google does allow up to 23 waypoints with a server-side request. So using PHP and JavaScript, I was able to make a workaround.
What you have to do is get the "waypoint order" from the server side request and then have JavaScript give you directions between each location.
<?php
$startLocation = "40.713,-74.0135";
$endLocation = "40.75773,-73.985708";
$waypoints = array("40.748433,-73.985656|", "40.689167,-74.044444|");
$apiKey = "";
$routeData = json_decode(file_get_contents("https://maps.googleapis.com/maps/api/directions/json?origin=".$startLoc."&destination=".$endLoc."&waypoints=optimize:true|".$waypoints."&key=".$apiKey));
echo "var waypointsOrder = ". json_encode($routeData->routes[0]->waypoint_order) . ";\n";
?>
var startLocation = {lat: 40.713, lng: -74.0135};
var endLocation = {lat: 40.75773, lng: -73.985708};
//get directions from the origin to the first waypoint
var request = {
origin: startLocation,
destination: JSON.parse(places[waypointsOrder[0]][1]),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderDirections(result, map);
}
});
//get directions from the last waypoint to the destination
var request = {
origin: JSON.parse(places[waypointsOrder[waypointsOrder.length-1]][1]),
destination: endLocation,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderDirections(result, map);
}
});
//get directions between each waypoint
for (i = 1; i < waypointsOrder.length; i++) {
var request = {
origin: JSON.parse(places[waypointsOrder[i-1]][1]),
destination: JSON.parse(places[waypointsOrder[i]][1]),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderDirections(result, map);
}
});
}
function renderDirections(result, map) {
var directionsDisplay = new google.maps.DirectionsRenderer ({
map: map
});
directionsDisplay.setMap(map);
directionsDisplay.setDirections(result);
}

Where in my Google maps code can I add Travel Mode to Directions?

I have directions working on my custom map. However I was hoping to add the pulldown I found on Google's Developer site that allows choices like "Bicycle", "Driving", "Transit", "Walking".
Here is my code that calls function I know not where they are:
var map;
var gdir;
var geocoder = null;
var addressMarker;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
gdir = new GDirections(map, document.getElementById("directions"));
GEvent.addListener(gdir, "load", onGDirectionsLoad);
GEvent.addListener(gdir, "error", handleErrors);
setDirections(document.getElementById("fromAddress").value, document.getElementById("toAddress").value, "en_US");
}
}
function setDirections(fromAddress, toAddress, locale) {
gdir.load("from: " + fromAddress + " to: " + toAddress,
{ "locale": locale });
}
and here is the URL and what I think is what I need put somewhere in what I have.
--I figure I can test it with just one mode, like "WALKING", first. Then add the pulldown once it works.
=====================================
URL I found this at:
https://developers.google.com/maps/documentation/javascript/examples/directions-travel-modes
=========================================
function calcRoute() {
var selectedMode = document.getElementById('mode').value;
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
This is in the code above and I want to use it
travelMode: google.maps.TravelMode["WALKING"]
I figured it out. I'm trying to add v3 features/syntax to v2. Doh! (slaps forehead)

How to geocode an address into lat/long with Google maps

I want to be able to plot several companies on a google map and understand I need to geocode these.
I also have the code below that plot's multiple markers on a map.
How can I Geocode several company addresses (using the following address as the first example) and incorporate it into the current code I have?
I really need someone's help as I can't make sense of the Google documentation as well as incorporating it with what I already have.
you could use google's geocoding to obtain coordinates of your post codes
EDIT: I don't really like you changing the sense of the question like that but ok. Please try sth like that (its not tested):
// Creating an array that will contain the coordinates
// for New York, San Francisco, and Seattle
var places = [];
// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var result;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=your+code&sensor=false",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
result = eval('(' + xmlhttp.responseText + ')');
if (result.status == "OK") {
var location = new google.maps.LatLng(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng);
places.push(location);
this should probably work, despite possible minor errors.
EDIT2: I have just now found simpler solution:
// Creating an array that will contain the coordinates
// for New York, San Francisco, and Seattle
var places = [];
// Adding a LatLng object for each city
//places.push(new google.maps.LatLng(40.756, -73.986));
//places.push(new google.maps.LatLng(37.775, -122.419));
//places.push(new google.maps.LatLng(47.620, -122.347));
//places.push(new google.maps.LatLng(-22.933, -43.184));
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "your+code"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//var marker = new google.maps.Marker({
//map: map,
//position: results[0].geometry.location
//});
places.push(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});

what Am i doing wrong in performing reverse geocoding

I am trying reverse geocoding, I have three coordinates and I want to convert them to addresses, I have used following method.
var point1 = new google.maps.LatLng(latLng1);
var point2 = new google.maps.LatLng(latLng2);
var point3 = new google.maps.LatLng(latLng3);
where latLng1, latLng2, latLng3 are coordinates.
and then further I want to use these addresses to following code to create a path
var request = {
origin:location1,
destination:location2,
waypoints:[{location: point1}, {location: point2}, {location: point3}],
travelMode: google.maps.DirectionsTravelMode.WALKING
};
but it never displays anything.
Am I doing it right, One more thing it says in google APIv3 that we can either use string of address in waypoint or latlng. how we can use latlag in waypoint.
Are you showing your whole code here?
Please, post your latLng1 value, for example.
Also, show your directionsService call. I do like that:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert(status);
});
In any case - try do alert() your request statuses, directions may not be available for these points.
By the way you don't need to reverse geocode your coordinates to addresses to get directions. You can use coordinates in waypoints, which is what you doing here.