I am getting back a ZERO RESULTS status when I make a call using the google directions service when I shouldn't, as far as I can see. I have walked through the debugger and it looks like my values are correct. I am using the directions service route method with waypoints. For origin, I need to use lat, lng vals because that is constantly changing, but for waypoints and destination, I use a full address. Waypoint addresses don't have country at end and stops at US state, but destination does have country value in the address. I wouldn't think that's a problem. All addresses are in the US, even in the same state.
Anybody see something wrong with my code and how it could be causing this, assuming the values being filled in are correct?
function setRoute() {
var wayPts = "";
var cAddress = $("#companyAddr").text();
//slice the zip code off
cAddress = cAddress.slice(0, -6);
var driverDisplay = $("#orders").find('.driverDisplay');
for (i = 0; i < driverDisplay.length; i++){
var directionsService = new google.maps.DirectionsService();
var dlats = $(driverDisplay[i]).find('.dLat');
var dlat = $(dlats[0]).text();
var dlngs = $(driverDisplay[i]).find('.dLng');
var dlng = $(dlngs[0]).text();
dLatLng = new google.maps.LatLng($('#driverLat').text(), $('#driverLng').text());
var stops = [];
var delAddrs = $(driverDisplay[i]).find('.dAddr');
for (var x = 0; x < delAddrs.length; x++) {
var delAddr = $(delAddrs[x]).text();
stops.push({ location: delAddr, stopover: true});
}
var request = {
origin: dLatLng,
destination: cAddress,
waypoints: stops,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.trace(status);
var data = response;
//$('#eta').text(response.routes[0].legs[0].duration.text);
}
//else { $('#eta').text("?") }
});
}
}
You create these variables but then don't seem to use them:
var dlats = $(driverDisplay[i]).find('.dLat');
var dlat = $(dlats[0]).text();
var dlngs = $(driverDisplay[i]).find('.dLng');
var dlng = $(dlngs[0]).text();
I think one problem might be here:
dLatLng = new google.maps.LatLng($('#driverLat').text(), $('#driverLng').text());
jQuery's text() function returns a string. Google Maps' LatLng constructor expects floating point numbers. Right now this is probably doing something like:
dLatLng = new google.maps.LatLng('1.234', '5.678');
You should make sure those are floats by doing:
dLatLng = new google.maps.LatLng(parseFloat($('#driverLat').text()), parseFloat($('#driverLng').text()));
Related
I'm trying to get the lat and lon from a Json encoded file for use as destinations for the distance Matrix API rather than add var destinationA = new google.maps.LatLng(??.????, ???.?????); multiple times.
I thought I managed it, as both ways seem to produce the same variable destinations when viewed, yet method two produces an error Uncaught TypeError: a.lat is not a function
This is method one which gives var destination a length of 7:
var destinationA = new google.maps.LatLng(13.7373393, 100.5558883);
var destinationB = new google.maps.LatLng(13.735132, 100.55611199999998);
var destinationC = new google.maps.LatLng(13.736953, 100.55819300000007);
var destinationD = new google.maps.LatLng(13.736244, 100.55694100000005);
var destinationE = new google.maps.LatLng(13.736166, 100.557203);
var destinationF = new google.maps.LatLng(13.738747, 100.55587700000001);
var destinationG = new google.maps.LatLng(13.733558, 100.56020699999999);
var destinations = [destinationA,destinationB,destinationC,destinationD,destinationE,destinationF,destinationG];
works great, will return the distances for each from a given centre point on google map.
Method two:
This is method Two which gives var destination a length of 1, which I am stuck on finding out why its a single length and not 7 as above:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
var first = true;
for (var i=0; i < location_lat_lon.length; i++) {
var sep = first ? '' : ',';
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(lat, lon);
var destinations = [destinations+sep+destination1] ;
first = false;
}
which returns exactly the same result when viewing the variable destinations, yet this returns the error Uncaught TypeError: a.lat is not a function.
Any advice or guidance?
Is it not possible to pass destinations this way to the calculateDistances function?
Thanks in Advance :)
Try this:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
for (var i=0; i < location_lat_lon.length; i++) {
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
destinations.push(destination1);
}
I want to delete a google map direction markers after a search without reloading the page. I've made an example but its not working :
//First of all testing if there is already a direction on the map
if(directionsService != null)
{
directionsService.setMap(null);
directionsService = null;
}
//Then display the new one
var origin = $('#de').val();
var destination = $('#en').val();
var request = {
origin : origin,
destination : destination,
travelMode : google.maps.DirectionsTravelMode.DRIVING
}
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status){
if(status == google.maps.DirectionsStatus.OK){
direction.setDirections(response);
showSteps(response);
}
});
all this code is on a function called by a click event
<button id="envoyer" id=="env" onclick="javascript:c()">Send</button>
so any one have an idea thanks !
Update
function showSteps(directionResult) {
var markerArray = [];
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
When clearing the itinerary, using directionsService.setMap(null); you will have to remove the MapMarkers, which aren't directly connected to the Direction - Service, seperately too.
You have already stored them in markerArray inside of your showSteps - function, so you would need to move this variable out of the function into an outer scope or let the function return it to be able to access it.
By doing this, you can simply loop over the markerArray and call .setMap(null) on each stored Marker, thus removing them from the map.
var markerArray = [];
function showSteps(directionResult){
// your code
}
//function to remove MapMarkers
function removeMapMarkers(){
for(var i=0; i<markerArray.length; i+=1){
markerArray[i].setMap(null)
}
markerArray = [];
}
I want to get back the elevation values from the code on the alert pop up like i am able to get the values of lat and lng. i am trying to get the three values (lat, lng and elevation heights) in an array so that i can later display the values using OpenGL but i am stuck on this part only as everything is working fine. This is the code i am using. thanks
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var nw = new google.maps.LatLng (ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
for(var i = 0 ; i<= (ne.lat() - sw.lat()); i+=0.01)
{ for(var j =0 ; j<=(ne.lng() - sw.lng());j+=0.01)
{
var tmpele; //temp variable for elevation<br/>
lt.push(sw.lat()+i);<br/>
ln.push(sw.lng()+ j);<br/>
var d = new google.maps.LatLng((sw.lat()+i),(sw.lng()+ j));
loca.push(d);
el.push(pospoint(loca));
} }
alert(lt);
alert(ln);
alert(el);
}
function disp()
{
alert(el);
}
function pospoint(loca)
{
var tmp;
var positionalRequest = {
'locations': loca
}
elevationService.getElevationForLocations(positionalRequest, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
tmp=results;
// alert('got:'+tmp);
// return tmp;
}
});
return tmp;
}
The elevation service is asynchronous. You can't return anything from it, you can only use the data (when it is available) in the callback function.
This is create a Google map to pass n number of address one time in Google map that is not possible that's way I am passing function set interval (2 sections ) to each iteration function
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var n;
var j=1;
var array_list= new Array(n);
var array_storename=new Array(n);
function InitializeMap()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions =
{
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionpanel'));
var control = document.getElementById('control');
control.style.display = 'block';
document.getElementById('sorttable').style.display="none"
}
function calcRoute(dist,varab)
{
n=document.getElementById('Countnumbers').value;
var start = document.getElementById('startvalue').value;
var end = document.getElementById(dist).innerHTML;
// end=end.replace(/[!##$%&^*()-+=|\/:;><~]/gi," ");
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
document.getElementById('sorttable').style.display="block";
document.getElementById("total").style.visibility="hidden";
directionsDisplay.setDirections(response);
var route = response.routes[0];
for (var i = 0; i < route.legs.length; i++)
{
var a=route.legs[i].distance.text;
var b=route.legs[i].duration.text;
var bc=a+",About :"+b;
var lblid="Labe"+varab;
document.getElementById(lblid).innerHTML=bc;
var store="lblstore"+varab;
document.getElementById(store).title=end;
var len=10.0;
var dd=route.legs[i].distance.value/1000;
array_list[varab]=dd;
array_list.sort(function(a,b){return a-b});
}
}
});
}
function Button1_onclick()
{
for(j=1;j<=n;j++)
{
document.getElementById('sorttable').style.display="block";
n=document.getElementById('Countnumbers').value;
var ss="lblstorename"+j;
var ss1 =document.getElementById(ss).innerHTML;
//this labels are store my addresss
calcRoute(ss,j);
}
}
//i am using google map in google map n number address are not go once thats way i am setTimeout (or) set interval method inside for loop
In order to add 2sec delay between each iteration, you need to recurrsively call ur calcRoute(..) and move your for-loop code inside calcRoute method.
Your code should look something like this -
function Button1_onclick() {
document.getElementById('sorttable').style.display="block";
n=document.getElementById('Countnumbers').value;
var ss="lblstorename"+n;//use n insteadof j
var ss1 =document.getElementById(ss).innerHTML;
calcRoute(ss,j);//only your first call is inside this method. rest all will be recurrsive
}
// making your calcRoute recurrsive
function calcRoute(ss, j){
//your code here
if(--j>0){
var ss="lblstorename"+j;
var ss1 =document.getElementById(ss).innerHTML;//not sure why are u using ss1
setTimeout(function(){calcRoute(ss, j)}, 2000);//here you set your time delay
}
}
The computeDistanceBetween() function in google maps geometry library will not return a value for me. Using the alert function it says the distance is "[object, Object]". Can anyone see where I'm going wrong? here are the important parts of the code in question:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script>
<script type="text/javascript" >
var myArray1= [['location1', lat1, lng1], ['location2', lat2, lng2], ...];
var myArray2= [['locationA', latA, lngA], ['locationB', latB, lngB], ...];
var arrays = [myArray1, myArray2];
function codeStart() {
var orig;
var startAddress = document.getElementById("start").value;
geocoder.geocode( { 'address': startAddress}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var i = 0;
var input = results[0].geometry.location;
while (i < arrays.length) {
orig = closest(input, arrays[i]);
}
}
});
}
function closest(latlng, array){
var distance;
var c = 0;
while (c < array.length){
var location = array[c];
var locationlatlng = new google.maps.LatLng(location[1],location[2]);
distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng);
alert(distance); // popup box says "[object, Object]"
c++;
}
}
</script>
computeDistanceBetween is a static method. So this line:
distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng);
should be this instead:
distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng)
By the way, when alert() tells you that something is an object, it's a good time to switch to console.dir() instead of alert() so you can (at least in some browsers) look at the contents of the object in the console/dev tools. If you don't know much about your JavaScript console, check it out. It will save you tons of time.
distance = new google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng);
For some reason you've used the syntax to create a new object. That is why, when you alert(distance), you're seeing that distance is an object.
computeDistanceBetween is just a function:
distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, locationlatlng);