I have two textbox in which we can enter locations & on button click route between two points shows in the map. Problem is on page it shows properly but when I use lighbox popup then map only shows grey color like below image. For pop up box I have used asp.net control modalpopupextender.
JS Code.
<script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
debugger;
var mumbai = new google.maps.LatLng(18.9750, 72.8258);
var mapOptions = {
zoom: 7,
center: mumbai
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var distance2 = response.rows[0].elements[0].distance.text; /*used for ID firstNumber*/
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
var firstNumber = document.getElementById("firstNumber");
var dvDuration = document.getElementById("dvDuration");
var dvDurationC = document.getElementById("dvDurationC")
dvDistance.innerHTML = "";
dvDistance.value = parseFloat(distance);
firstNumber.innerHTML = distance2 /*used for ID firstNumber*/
dvDuration.innerHTML = duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
Try making these two changes:
Remove the display property and set visibility: hidden on #map.
Move #map to a place where the space it inhabits won’t be noticed. Right before is probably a good choice.
Refer to this tutorial.
Related
Im trying to find the distance matrix between two points in Google Maps API and im getting this error.
Uncaught TypeError: Cannot read property 'apply' of undefined
at distance_matrix.js:4
at Ku.j (distance_matrix.js:3)
at Object.c [as _jr083s] (common.js:110)
at DistanceMatrixService.GetDistanceMatrix?1m1&2s35.853308276088036&1m1&2s-
Im trying to get the distance matrix response so I can get the distance in miles. Heres the code that I have
function initMap() {
const momilets = { lat: 35.853308276088036, lng: -78.57256943168214};
const map = new google.maps.Map(document.getElementById('map'), {zoom: 12, center: momilets, disableDefaultUI: true});
const marker = new google.maps.Marker({position: momilets, map: map});
const geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', () => {
geocodeAddress(geocoder, map);
})
}
function geocodeAddress(geocoder, resultsMap) {
const address = document.getElementById('address').value;
geocoder.geocode({ address: address }, (results, status) => {
if(status = 'OK') {
resultsMap.setCenter(results[0].geometry.location);
const marker2 = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
});
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: ['35.853308276088036', '-78.57256943168214'],
destinations: [toString(lat), toString(lng)],
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: 'DRIVING'
} );
} else {
alert("Unsuccessful because: " + status);
}
});
}
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}
if anyone can help clear this error for me itd be greatly appreciated
you haven't provided callback function in service.getDistanceMatrix() method that's why getting the above error.
service.getDistanceMatrix({
origins: ['35.853308276088036', '-78.57256943168214'],
destinations: [toString(lat), toString(lng)],
unitSystem: google.maps.UnitSystem.IMPERIAL,
travelMode: 'DRIVING'
}, (response, status) => {
console.log("response data: ", response);
console.log("status: ", status);
});
You can follow the below JSFiddle link for complete working code.
<script async src="//jsfiddle.net/y4zbkudo/4/embed/js,html,css,result/dark/"></script>
Hi is it possible to get the direction from googlemaps without showing a map?
I can get the directions from calling like this:-
https://maps.googleapis.com/maps/api/directions/json?origin=52.4076963,-1.4853391999999985&destination=52.6114729,-1.6812878000000637&key=KEYHERE
<div id="result"></div>
And the code I am trying to call it with is :
function calcRoute() {
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var result = document.getElementById('result');
result.innerHTML= "";
for (var i =0; i < response.routes[0].legs[0].steps.length; i++){
result.innerHTML+=response.routes[0].legs[0].steps[i].instructions+"<br>"
}
console.log(response)
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
How I get this to run with calcRoute and just show the direction in the div?
Thanks
To display the directions text without a map using the Google Maps Javascript API v3:
don't set the map property of the DirectionsRenderer
set the panel property of the DirectionsRenderer
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
proof of concept fiddle
function initialize() {
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="result"></div>
The solution to a lot of "how to use the maps API without showing a map?" questions assumes that it's going to be ok to use setPanel and for a journey plan to appear on your page instead of a map.
In case anyone wondered, if you don't want this and just want to extract data from the API without any google html being injected into your page at all you still need to use setPanel, but parse a null to it.
directionsDisplay.setPanel(null);
I need to get a route between 2 location in asp, since I want variables to improve my page navigation. I found an excellent method online that works wonders, but it activates a onclick function to work. I need to reload the page to obtain variables from my database.
The original version is this one:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var rome = new google.maps.LatLng(41.918357, 12.485029);
var mapOptions = {
zoom: 4,
center: rome
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "<strong>" + "Distanza:" + "</strong>" + " " + distance + "<br />";
dvDistance.innerHTML += "<strong>" + "Durata:" + "</strong>" + " " + duration;
} else {
alert("Impossibile trovare la distanza stradale");
}
});
}
</script>
it's activated by a onclick="GetRoute()" command in the request form, where I input my departure and destination in two fields. It will then display a map with the two locations with the route informations by its side.
Now, what I want, is to activate it with asp, since I need to access my sql.So the button type will become a submit without the onclick instruction, the page will reload, I'll get the data I need questioning my database and the gmaps script will run as usual, automatically triggering that GetRoute() function. I hope I've been clear, my english is a bit rusty, I could provide the work in progress address where I'm trying to fix this bad boy.
I'd like the whole script to be activated automatically after the page is reloaded, without the onclick command. So, basically, I want to get rid of the GetRoute() command. As long as I have the data needed by the script (txtSource and txtDestination), is there a way to obtain my map and route, once the page has reloaded?
You could do this with a slight modification to your existing code,
using the GetRoute function, without the onclick:
In the GetRoute function, set the source and destination variables to the request values:
function GetRoute()
{
source = "<%=Request("txtSource")%>";
destination = "<%=Request("txtDestination")%>";
if( source != "" && destination != "")
{
/*the rest of your code as is,except the following change:
comment out the following two lines, as we are already setting this with the request values
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
*/
}
}
And in the html, for the body tag, add <body onload="GetRoute();"> so that the function will be called after all the elements are loaded.
thank you for your help. I used your suggestions and the map appears, but without the route, so maybe I did something wrong in the code. I can confiirm that the two requests (txtsource and txtdestination) are passed correctly.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script><script type="text/javascript">
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute()
{
source = "<%=Request.form("txtSource")%>";
destination = "<%=Request.form("txtDestination")%>";
if( source != "" && destination != "")
{
var rome = new google.maps.LatLng(41.918357, 12.485029);
var mapOptions = {
zoom: 4,
center: rome
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
/*source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
*/
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "<strong>" + "Distanza:" + "</strong>" + " " + distance + "<br />";
dvDistance.innerHTML += "<strong>" + "Durata:" + "</strong>" + " " + duration;
} else {
alert("Impossibile trovare la distanza stradale");
}
});
}
}
</script>
Edit: I have divs in my HTML for the map and the route. That doesn't appear to be the problem, since the map shows, but I have no route on it
<div class="row">
<div class="col-md-6">
<div id="dvMap" style="height: 500px"></div>
</div>
<div class="col-md-6" style="height:500px; overflow-x:hidden; overflow-y:auto;">
<div id="dvPanel" ></div>
</div>
With the code below, I display a journey betwen two points.
Now I try to use direction result object and direction leg to get information like steps, legs or distance in a variable, but I have no idea to how use this method...
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(44.912198, -0.605530);
var oceanBeach = new google.maps.LatLng(44.893356, -0.739138);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute()
}
calcRoute()
function calcRoute() {
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.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Thanks
I've resolved a part of the problem with this code :
Variable duration, path, and polyline1 are ok, I've tried it with an alert.
Now I want to save those variables in a data base like sql, how I do ? using php ?
function calcRoute() {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var duration = myRoute.steps[i].duration.text;
var path = myRoute.steps[i].path;
var polyline1 = myRoute.steps[i].distance.text;
}
}
Im using below code to show a distance between two distances but zoom doesn't work it always will be in default zoom level. I tried setting lot of values but it's not working. Please help.
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var from = "";
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.preserveViewport = false;
var dallas = new google.maps.LatLng(32.8931567, -97.0402193);
var mapOptions = {
zoom: 15,
center: dallas
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
map.setZoom(map.getZoom()+5);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = 'dallas airport terminal a';
var end = 'SpringHill Suites';
console.log("HotelDetail: " + end);
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
For what you want to achieve, the preserveViewport property needs to be set to true like this.
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true
});
//directionsDisplay.preserveViewport = false;
In addition, your code sets a zoom level of 20 which is too high to see anything on the map. Here is a working example with an initial zoom level of 12: JSFiddle