Getting TravelTime from Google Maps API for Javascript - javascript

I am trying to get travel time with traffic between two locations.
I have followed the documentation guide with all details, but I always get a fixed traveltime between two points regardless to trafficmodel: (best_guess, pessimistic or optimistic).
Also, I tried to change the value of departure time to different dates in future but I always get the same result.
Edit:
I am using a standard API key.
Also, I have tried to change date format for [departureTime:] but did not help.
My main goal is to get travel time on links with traffic.
Thanks for helping.
Here is my HTML and Javascriptcode:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Displaying text directions with <code>setPanel()</code></title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
height: 100%;
float: right;
width: 390px;
overflow: auto;
}
#map {
margin-right: 400px;
}
#floating-panel {
background: #fff;
padding: 5px;
font-size: 14px;
font-family: Arial;
border: 1px solid #ccc;
box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
display: none;
}
#media print {
#map {
height: 500px;
margin: 0;
}
#right-panel {
float: none;
width: auto;
}
}
</style>
</head>
<body>
<div id="floating-panel">
<strong>Get TravelTime in Traffic</strong>
</div>
<div id="right-panel"></div>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]&callback=initMap">
</script>
<script>
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 30.114114, lng: 31.420595}
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var control = document.getElementById('floating-panel');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: "11 The Ring Road, Al Khosous, Al Khankah, Al Qalyubia Governorate, Egypt",
destination: " El-Shams Sporting Club, Al Matar, Qism El-Nozha, Cairo Governorate, Egypt",
travelMode: google.maps.TravelMode.DRIVING,
drivingOptions: {
departureTime: new Date("June 14, 2016 11:13:00"),
trafficModel: google.maps.TrafficModel.PESSIMISTIC
}
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
</body>
</html>

It seems this has nothing to do with your code. Instead, it is a matter of licensing. Your are using Driving Options (BEST_GUESS, OPTIMISTIC,PESSIMISTIC) which is a feature that belongs to Premium Plan clients. The way I see it, you need to buy the license first and use the Premium clientID before you can use this.
"You must supply a Google Maps APIs Premium Plan client ID when
loading the API if you want to include a drivingOptions field in the
DistanceMatrixRequest."
Your client ID
Upon purchasing your Google Maps APIs Premium Plan license, you will receive a welcome email from Google that contains your client ID. Your client ID is used to access the special features of Google Maps APIs Premium Plan. All client IDs begin with a gme- prefix.
This client ID is not a key. It will only work from URLs which you authorize, so you don't need to worry about keeping it secret.

Maybe your date format is not correct ?
Try :
departureTime: new Date("2016-06-14T11:13:00");

Related

Google Maps: How do you embed it WITH search bar?

Hey I'm trying to integrate Google Maps into a website. Embedding Google Maps at a certain map location is quite easy, since you can generate the code for embedding on google maps itself through the share button, but this hides the search bar which I need for my game.
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d193595.15830869428!2d-74.119763973046!3d40.69766374874431!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x89c24fa5d33f083b%3A0xc80b8f06e177fe62!2sNew%20York%20City%2C%20New%20York%2C%20USA!5e0!3m2!1sde!2sde!4v1573800931555!5m2!1sde!2sde" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen=""></iframe>
Throughout the website players get coodrinates which you can enter into google maps to be shown the right location. Though what i would like to do is use the default google maps within an iframe for example so people can read and enter these coordinates without having to switch pages constantly.
Is there a way to do this, or do i have to pay for that? I'm currently looking into alternative map providers.
As was noted in the comments this is probably not possible via the simple iframe embed.
However, if you use the Google Maps API, there is ample documentation for that found here.
A quick example from the docs:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Search Box</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html>
Also, I accidently revoked my flag but I noticed that this question could be closed as a duplicate of a number of questions, for example: here, here, and here.
Most of the issues were solved by switching to open street maps. I can just use an iframe with a link to their website. It's not quite perfect yet but I may be able to customize it enough to work smoothly.

reverse geocoding without map

Using the below code to find local area from longitude and latitude, i'm not really wanting a specific address, just city or state.
The problem is that all I need is the city placed in to a variable, I dont want the map. Is this possible
I have taken this code from google developers site and put an alert box to display the address, which is fine, but dont want the map.
I have come across this which returns details from long/lat,
https://maps.googleapis.com/maps/api/geocode/json?
latlng=55.056499,1.600130&key=XXX&sensor=false
But getting this message - although not exceeding limit
{
"error_message" : "You have exceeded your daily request quota for this API. If
you did not set a custom daily request quota, verify your project has an
active billing account: http://g.co/dev/maps-no-account",
"results" : [],
"status" : "OVER_QUERY_LIMIT"
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Reverse Geocoding</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#floating-panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
</style>
</head>
<body>
<div id="floating-panel">
<input id="latlng" type="text" value="40.714224,-73.961452">
<input id="submit" type="button" value="Reverse Geocode">
</div>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.731, lng: -73.997}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click',
function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng:
parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0])
{
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
// infowindow.setContent(results[0].formatted_address);
// infowindow.open(map, marker);
window.alert(results[0].formatted_address);
}
else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XX&callback=initMap">
</script>
</body>
</html>

Google Maps + Streetview issue - How to disable Photo Sphere

So on my site I'm using Google Maps + Streetview:
https://developers.google.com/maps/documentation/javascript/examples/streetview-simple
Also I'm using standard searchbox with autocomplete, the problem is when I enter some locations, there is no streetview, just Photo Sphere image without any controls for moving around like in standard streetview...
I really don't want Photo Sphere, because I want my users to freely move around with street view, and now they sometimes get "trapped" in one Photo Sphere image... Is there a way I can force streetview without Photo Sphere?
I'm not sure how to turn off PhotoSpheres, but I did find a workaround that may be useful to you. I noticed at https://developers.google.com/maps/documentation/javascript/reference#StreetViewSource that when searching for a location, if you set the source to OUTDOOR, then PhotoSpheres are not returned.
Therefore, if you add listeners for location changes, and then search for the location without PhotoSpheres, I think you should be able to prevent them from showing up.
Here is a modified google maps example to illustrate:
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete without PhotoSpheres</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map, #pano {
height: 100%;
width: 50%;
float:left;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map"></div>
<div id="pano"></div>
<script>
var map;
var panorama;
var streetViewService;
var DEFAULT_PROXIMITY = 50;
var MAX_PROXIMITY = 10000;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = /** #type {!HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
//autocomplete.bindTo('bounds', map);
streetViewService = new google.maps.StreetViewService();
panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: {lat: -33.8688, lng: 151.2195},
pov: {
heading: 34,
pitch: 10
}
});
map.setStreetView(panorama);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.location) {
findClosestStreetView(place.geometry.location, DEFAULT_PROXIMITY);
}
});
function findClosestStreetView(point, proximity) {
streetViewService.getPanorama({location: point, radius: proximity, source: google.maps.StreetViewSource.OUTDOOR}, function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
map.panTo(data.location.latLng);
panorama.setPano(data.location.pano);
} else {
if (proximity < MAX_PROXIMITY) {
findClosestStreetView(point, proximity + 50);
} else {
// NO PANARAMA FOUND - do something else here...
panorama.setVisible(false);
}
}
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?&libraries=places&callback=initMap" async defer></script>
</body>
</html>

No map showing even though simple code

I'm trying to make a map adding a marker on the users location (accompanied by a searchbox) but even though my Javascript seems legit I can't figure out what seems to be the problem.
Background info:
I'm in the beginning of my learning, explaining all of the many and unnecessary divs with accompanying CSS. There seems to be no problem with the code, either the CSS or the Javascript, but still the map doesn't show up on the screen. The map has worked, unfortunatly the code is gone, when there was a standard center (set with cordinates).
If more info is requiered and/or presented in a different way, please let me know. There is a working snippet for testing. Just click "Run code snippet".
function initialize(position) {
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var setting = {
center: location,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), setting);
var marker = new google.maps.Marker({
position: location,
map: map,
title: 'Marker'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize);
}
google.maps.event.addDomListener(window, 'load', initialize);
.mapContent {
padding: 0;
height: 500px;
padding: 0;
margin: 60px auto;
}
.mapContainer {
width: 830px;
padding: 0;
margin: 0 auto;
}
div #googleMap {
height: 500px;
width: 500px;
float: left;
border-radius: 250px;
margin-right: 30px;
}
div #searchbox {
float: left;
height: 400px;
width: 300px;
background: white;
margin-top: 50px;
}
#floating-panel {
z-index: 5;
background-color: darkred;
padding: 5px;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
border-radius: 5px;
}
<div class="mapContent">
<div class="mapContainer">
<div id="searchbox">
<div id="floating-panel">
<input id="address" type="textbox" value="">
<input id="submit" type="button" value="Sök">
</div>
</div>
<div id="googleMap"></div>
</div>
</div>
You have the following error on your page:
“Uncaught ReferenceError: google is not defined”
Remember that the API can not be loaded after the document has finished loading you'll need to do that asynchronously.
Also, you may have forgotten to add the api URL reference: https://maps.googleapis.com/maps/api/js
Check out this fiddle, everything works perfectly:
https://jsfiddle.net/eugensunic/wexd3spp/6/
Code to enable the navigation:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize);
}
google.maps.event.addDomListener(window, 'load', initialize);

Connecting Values to Function after Click Event

I'm trying to implement text search fields in the Google Places API, I created text fields as well as a click event that leads to the 'calcRoute()' function. I'm having trouble setting the in the text fields to the variable 'start' and 'end' (at least I think that's the porblem). Can anyone help me out? The directions list should appear on the right of the map.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Displaying text directions with <code>setPanel()</code></title>
<style>
html, body, #map-canvas {
height: 80%%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<style>
#directions-panel {
height: 80%%;
float: right;
width: 390px;
overflow: auto;
}
#map-canvas {
margin-right: 400px;
}
#control {
background: #fff;
padding: 5px;
font-size: 14px;
font-family: Arial;
border: 1px solid #ccc;
box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
display: none;
}
#media print {
#map-canvas {
height: 500px;
margin: 0;
}
#directions-panel {
float: none;
width: auto;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"> </script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.TRANSIT
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="control">
<strong>Start:</strong>
<input type="text" data-bind="value:start"/>
<strong>End:</strong>
<input type="text" data-bind="value:end"/>
<button onclick="calcRoute()">Get Directions</button>
</div>
<div id="directions-panel"></div>
<div id="map-canvas"></div>
</body>
</html>
I think you're using getElementById without setting any IDs in your HTML
<!-- Elements don't have IDs -->
<input type="text" data-bind="value:start"/>
<input type="text" data-bind="value:end"/>
Try this:
<input id="start" type="text" data-bind="value:start"/>
<input id="end" type="text" data-bind="value:end"/>
Now when this code gets called, the elements should be found
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;

Categories