google maps javascript api does not get me any adress - javascript

I am using this code ,
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
above code works fine.But when I changed the part below,it gives me error code "Directions request failed due to zero_results".because of it can not find this coordinat (36.9165612, 34.895210200000065) in map.But actually I am getting this coordinats another google api.so this coordinat exists.Even it finds the address in google map https://www.google.com.tr/maps/place/36.9165612,+34.895210200000065/data=!4m2!3m1!1s0x0:0x0?sa=X&ved=0ahUKEwiB6OT03JjNAhWLLMAKHZrIApgQ8gEIGjAA
lastly when I change to coordinat to (41.85, -87.65), it works fine coz it finds the address.Many less coordinats works like this.
I want to find all coordinats in google maps.
How can I solve this problem?
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: new google.maps.LatLng(36.9165612, 34.895210200000065),
stopover: true
});
}
}

It may not find an address from a lat and lng. You have to consider it.
More info here and here

Related

Access javascript variable

I'am trying to create a web app with google map direction API,In a variablesummaryPanel.innerHTMLContains the details regarding the address and distance.I required to use distance for other calculations ,so how can i access the variable,can we access the variable from the angular controller?
script.js
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected) {
waypts.push({
location: checkboxArray[i].value,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
console.log(summaryPanel.innerHTML);//Variable required to access
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
Using jQuery:
var htmlString = $(summaryPanel).html();
Then you'll have to parse whatever htmlString comes out to, but it will have what you're looking for.
Source: http://api.jquery.com/html/

Google Maps Javascript API - Results Formatting

I need to display the results of a distance matrix request without geocoding. The problem is my locations are too close together and thus the resultant geocoded addresses are the same.
If I could display the results with the variable names or even the original lat/lon coordinate pairs I would be able to distinguish between the locations.
I checked the documentation for the Distance Matrix Response Elements and I did not see this functionality.
The javascript is below.
function initMap() {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
var origin1 = {lat: 37.2692332704, lng: -81.7261622975};
var origin2 = {lat: 37.2625193371, lng: -81.7183645359};
var origin3 = {lat: 37.1315998981, lng: -81.8552666961};
var destinationA = {lat: 37.1854557602, lng: -81.7946133276};
var destinationB = {lat: 37.1751720467, lng: -81.792833926};
var destinationC = {lat: 37.1595851233, lng: -81.8570206921};
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.2692332704, lng: -81.7261622975},
zoom: 8
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2,origin3],
destinations: [destinationA, destinationB,destinationC],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
var showGeocodedAddressOnMap = function(asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(bounds.extend(results[0].geometry.location));
markersArray.push(new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
}));
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
//geocoder.geocode({'address': originList[i]},
//showGeocodedAddressOnMap(false));
for (var j = 0; j < results.length; j++) {
//geocoder.geocode({'address': destinationList[j]},
//showGeocodedAddressOnMap(true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
}
}
}
});
}
Thanks in advance.
The results are returned in the order requested.
origin1 - destination1
origin1 - destination2
origin1 - destination3
origin2 - destination1
---
origin3 - destination3
You can use your original request to identify the exact coordinates used to calculate the result.
proof of concept fiddle
code snippet:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var destinationIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?' +
'chst=d_map_pin_letter&chld=O|FFFF00|000000';
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 37.2692332704,
lng: -81.7261622975
},
zoom: 8
});
var originArray = [origin1, origin2, origin3];
var destinationArray = [destinationA, destinationB, destinationC];
for (var i = 0; i < originArray.length; i++) {
var oMarker = new google.maps.Marker({
position: originArray[i],
map: map,
label: "" + i,
icon: originIcon
});
bounds.extend(oMarker.getPosition());
}
for (var i = 0; i < destinationArray.length; i++) {
var dMarker = new google.maps.Marker({
position: destinationArray[i],
map: map,
label: "" + i,
icon: destinationIcon
});
bounds.extend(dMarker.getPosition());
}
map.fitBounds(bounds);
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: originArray,
destinations: destinationArray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
outputHTML = "";
outputHTML += "<table border='1'><thead><tr><th>Oi</th><th>origin</th><th></th><th>Di</th><th>destination</th><th>distance</th><th>duration</th></tr></thead><tbody>";
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputHTML += "<tr><td>O" + i + "</td><td>" + originArray[i].lat + "," + originArray[i].lng + "</td><td> to </td><td>D" + j + "</td><td>" + destinationArray[j].lat + "," + destinationArray[j].lng +
"</td><td>" + results[j].distance.text + "</td><td> in " +
results[j].duration.text + "</td></tr>";
}
}
outputHTML += "</tbody></table>";
outputDiv.innerHTML = outputHTML;
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
var origin1 = {
lat: 37.2692332704,
lng: -81.7261622975
};
var origin2 = {
lat: 37.2625193371,
lng: -81.7183645359
};
var origin3 = {
lat: 37.1315998981,
lng: -81.8552666961
};
var destinationA = {
lat: 37.1854557602,
lng: -81.7946133276
};
var destinationB = {
lat: 37.1751720467,
lng: -81.792833926
};
var destinationC = {
lat: 37.1595851233,
lng: -81.8570206921
};
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="output"></div>
<div id="map"></div>

For loop inside waypoints - Google Maps [duplicate]

This question already has an answer here:
Google Directions Service with Waypoints not working
(1 answer)
Closed 8 years ago.
I am trying to display a route with waypoints for a trip. I save all the coordinates to a MySQL varchar attribute and then pull it out with php and slice it up into an array so the two array elements fruits[0] and fruits[1] represent the start, the fruits[2] and fruits[3] represent the first waypoint, that is the second place visited and so on.
I am trying to display the route of the trip and it works perfectly if I don't use waypoints, that is, if I don't populate the waypts array with all points except start and finish.
This is my code
<style>
#map-canvas {
width: 100%;
height: 400px;
}
</style>
<script type="text/javascript">
var fruits = <?php echo json_encode($arr); ?>;
for (var i = 0; i < fruits.length; i+=2) {
//text += cars[i];
}
</script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var dbk = new google.maps.LatLng(fruits[0], fruits[1]);
var mapOptions = {
zoom: 11,
center: dbk,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var waypts = [];
for (var i = 2; i < fruits.length -2; i+=2) {
waypts.push(new google.maps.LatLng(fruits[i], fruits[i+1]));
};
var request = {
origin: new google.maps.LatLng(fruits[0], fruits[1]),
destination: new google.maps.LatLng(fruits[fruits.length-2],fruits[fruits.length-1] ),
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
} else {
alert("directions response "+status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to use Directions Waypoints for the waypoints.
var waypts = [];
for (var i = 2; i < fruits.length -2; i+=2) {
waypts.push({
location:new google.maps.LatLng(fruits[i], fruits[i+1]),
stopover:true
});
};
Working example with single LatLng waypoint

Giving each Google Distance Matrix result an id

I am using the Google Distance Matrix https://developers.google.com/maps/documentation/distancematrix/
to calculate some delivery charges. When it outputs the results in the for loop it puts them onto a new line each time, so I end up with :
1
25
26
1
Is it possible to store each result in a variable so I can call each individual result elsewhere in the code for some maths to work out costs etc, so.....
$result1
$result2
$result3
$result4
As later on I would like to do things like result1 * result3 = etc etc.
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var base = new google.maps.LatLng(55.930385, -3.118425);
var start = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var end = new google.maps.LatLng(55.930385, -3.118425);
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
calculateDistances();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [base],
destinations: [start, end],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '<table border="1">';
deleteOverlays();
var stringArray = ['$runinPickup','$runinDestination'];
var htmlString = '<table border="1">';
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
outputDiv.innerHTML += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
}
}
htmlString += '</table>';
// outputDiv.innerHTML += '</table>';
outputDiv.innerHTML = htmlString;
// alert(htmlString);
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Well that shouldn't be too hard. Where you output the value, e.g.
htmlString += '<tr><td>'+stringArray[j]+'</td><td>' + results[j].distance.text +'</td></tr>';
Simply add an additional line assigning that value into a variable. I'd be inclined to add them into an array which you can loop over later.
arrResults.push(results[j].distance.text);
If you're confident you always know what each value will be, then you can simply refer to them like arrResults[0] * arrResults[2]

Google Maps API: Total distance with waypoints

I'm trying to calculate the total distance for a route with a single waypoint in it, but somehow my code only returns the distance to the first waypoint instead of the total distance.
Here's my code:
function calcRoute(homebase,from,to,via){
var start = from;
var end = to;
var wypt = [ ];
wypt.push({
location:via,
stopover:true});
var request = {
origin:start,
destination:end,
waypoints:wypt,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.METRIC
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var distance = response.routes[0].legs[0].distance.text;
var time_taken = response.routes[0].legs[0].duration.text;
var calc_distance = response.routes[0].legs[0].distance.value;
}
});
}
The reason you only get the distance for legs[0] is because that is what your code is calculating. You need to sum up the distances of all the legs:
http://www.geocodezip.com/v3_GoogleEx_directions-waypoints_totalDist.html
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
google.maps.event.addDomListener(window, 'load', initialize);
function calcRoute() {
var request = {
// from: Blackpool to: Preston to: Blackburn
origin: "Blackpool,UK",
destination: "Blackburn,UK",
waypoints: [{
location: "Preston,UK",
stopover: true
}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
computeTotalDistance(response);
} else {
alert("directions response " + status);
}
});
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="total"></div>
</div>

Categories

Resources