Issue is Google Maps API display directions from one location to another is returning error function displayDirections() is not defined.
Unsuccessful with help from other questions so far, ex here, or here
Full code here, been fidgeting with the quotes and single quotes etc but don't think that's the issue. This function is listed where all my other functions are called without issues. When I enter in a destination, then when the infoWindows appear, I select the View Route button, but I still get the error that displayDirections is not defined, I even moved this function up global in App.js, but I still can't figure out why this function is
Just a snip it of the code, if something's missing it's probably in the full code;
function displayDirections(origin) {
hideListings()
let directionsService = new window.google.maps.DirectionsService()
let destinationAddress = document.getElementById('search-within-time-text').value
let mode = document.getElementById('mode').value
directionsService.route({
origin: origin,
destination: destinationAddress,
travelMode: window.google.maps.TravelMode[mode]
}, function(response, status) {
if (status === window.google.maps.DirectionsStatus.OK) {
let directionsDisplay = new window.google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'green'
}
}) } else {window.alert('Directions request failed due to ' + status)
}
})
}
let infowindow = new window.google.maps.InfoWindow({ content: durationText + ' away,
' + distanceText + '<div><input id="route" type="button" value="View Route" onclick
=' + '{displayDirections("origins[i]")}></input></div>'})
Is this supposed to be a template literal:
onclick=displayDirections(`${origins[i]}`)
Related
I have this code that gets the data from postgis and but when launching my page my markers won't show, even though there is no error in the console. the problem seemes to come from couche.on('data:loaded', function (e) since apparently it's not able to get the loaded data and because when i do couche.addTo(maCarte) directly the markers show. And i tried it in a another example with var couche = new L.GeoJSON.AJAX("data/markers.geojson", { and it works.
Another problem is when i enter a variable to select a specefic marker i always get the same error Uncaught SyntaxError: Unexpected token < in JSON at position 2 even though i checked my php file and it's fine and show the results when i launched directly Exécution du script PHP it happens in this code only when i add a variable and when there is none and the variable is null, the data is downloaded without any problem, so i don't know where the problem is coming from.
Can anyone please help me find a solution ?
function loadData() {
console.log('php/lecture.php?var=' + variable )
$.ajax({url:'php/lecture.php?var=' + variable ,
success: function(response){
data = JSON.parse(response)
console.log(data)
console.log('Données téléchargées : ' + response.length / 1000000 + 'Mo')
drawEntities(data)
maCarte.fitBounds(couche.getBounds())
}
})
}
couche = new L.GeoJSON(data.features, {
onEachFeature: function (feature, layer) {
layer.bindPopup('<h4>date_debut: ' + feature.properties.date_debut+
'</h4>')
},
pointToLayer: createCircleMarker
});
couche.on('data:loaded', function (e){
function makeGroup(color) {
return new L.MarkerClusterGroup({
iconCreateFunction: function(cluster) {
return new L.DivIcon({
iconSize: [20, 20],
html: '<div style="text-align:center;background:'+color + '">' +
cluster.getChildCount() + '</div>'
});
}
}).addTo(maCarte);
}
var groups = {
TR: makeGroup('red'),
DE: makeGroup('green'),
CA: makeGroup('orange'),
CO: makeGroup('blue')
};
e.target.eachLayer(function(layer) {
groups[layer.feature.properties.type].addLayer(layer);
});
});
}
I pass php $var into Javascript from controller. $var has fetched addresses from DB. And i put it in Javascript. Now i can see the addresses in the console. No problem with that, I don't know why syntax error pop up too.
This is how I insert it into JS.
function initMap(){
var options = {
zoom:8,
center:
'{!! $estates[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($estates as $addr)
'{!! $addr->address !!}',
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
my foreach running without a problem I can see the addreses in the console but also at this line: '{!! $estates[0]->address !!}' error pops up too. Actually I am seeing the address not this line.
error is this:
Uncaught SyntaxError: Invalid or unexpected token
Do you have any idea? am I making syntax mistake. But if do that then how can I retrieving the addresses at the console?
Also having this error too at the same line:
Undefined variable: estates (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php) (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php)
Controller
public function index()
{
$estates = DB::table("allestates")
->get();
return view("home", compact('estates'));
}
the topic is different the duplicated ones. it's not pure JS i am working with Laravel.
I think one of the addresses contains the ' character. To avoid it use the addslashes function. You could do that in the controller:
public function index()
{
$estates = DB::table("allestates")->get()->map(function($estate) {
$estate->address = addslashes($estate->address);
return $estate;
});
return view("home", compact('estates'));
}
And the according js would be:
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
Because you have multiple addresses, it means you will have multiple markers too. That being said your code should look something like:
function initMap(){
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
var map = new google.maps.Map(document.getElementById("map"), options);
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
var markers = [];
#foreach ($estates as $key => $estate)
markers[{{$key}}] = new google.maps.Marker({
position: new google.maps.LatLng({{$estate->lat}}, {{$estate->long}});
map: map
});
markers[{{$key}}].addListener('click', function () {
infoWindow.open(map, markers[{{$key}}]);
});
#endforeach
}
You can use php variables inside laravel blade files as
var options = {
zoom:8,
center:
'{{$estates[0]->address}}'
}
I am working on a google maps API project.
I take lat and long values from a database and display them in HTML rendered by PHP.
I want to draw a route on map when I click the button with the lat&long values. ( check the image http://imgur.com/DkxlFbC )
But there is something going wrong and always taking the same values to draw the route.
I try to use changehandler but does not work.
index.php:
<?php
$test=mysql_query("SELECT lat, lng FROM markers ");
?>
<div class='container'>
<div class='row'>
<center>
<?php
while ($deneme=mysql_fetch_assoc($test)) {
extract($deneme);
echo '<br>';
echo '<h6 id="lat" class="box-design">'.$deneme['lat'].'</h6>';
echo '<h6 id="lng" class="box-design">'.$deneme['lng'].'</h6>';
echo '<br>';
echo '<input id="submit" onclick="myFunction()" type="submit" class="btn btn-primary" value="Button">';
echo '</div>';
}
?>
</center>
</div>
</div>
JS:
function myFunction() {
infoWindow = new google.maps.InfoWindow;
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions:{strokeColor:"#4a4a4a",strokeWeight:5}, suppressMarkers:true });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
directionsDisplay.setMap(map);
destLatLng = new google.maps.LatLng(document.getElementById('lat').textContent, document.getElementById('lng').textContent);
directionsService.route({
origin: pos,
destination: destLatLng,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
Like was mentioned in comments, the id attribute needs to be unique.
The id global attribute defines a unique identifier (ID) which must be unique in the whole document. 1
Use a technique like the one below to add a numeric index to each set of latitude and longitude values with associated buttons. Notice the last reference (i.e. onclick="myFunction('.$index++.')") uses the post-increment operator to increase the index for the next iteration of the while loop.
$index = 1;
while ($deneme=mysql_fetch_assoc($test)) {
extract($deneme);
echo '<br>';
echo '<h6 id="lat'.$index.'" class="box-design">'.$deneme['lat'].'</h6>';
echo '<h6 id="lng'.$index.'" class="box-design">'.$deneme['lng'].'</h6>';
echo '<br>';
echo '<input id="submit" onclick="myFunction('.$index++.')" type="submit" class="btn btn-primary" value="Button">';
echo '</div>';
}
Then since the javascript function myFunction() will now be passed an integer , that argument (e.g. named index) can be used to find the associated latitude and logitude values (or those could be used as arguments to in the function call instead).
So update the function definition to include that argument:
function myFunction() {
becomes:
function myFunction(index) {
and then this line:
destLatLng = new google.maps.LatLng(document.getElementById('lat').textContent, document.getElementById('lng').textContent);
can be updated to use that index:
destLatLng = new google.maps.LatLng(document.getElementById('lat' + index).textContent, document.getElementById('lng' + index).textContent);
Also, to re-use the same directions service and directions renderer, declare those at the start of the javascript, and then initialize them in the function that initializes the map (e.g. initMap()):
var map, pointA, directionsService, directionsDisplay;
function initMap() {
var options = {};
/*
code to setup options
*/
map = new google.maps.Map(document.getElementById('map-canvas'), options);
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer({ /* ... */});
}
That way the code in myFunction() can just directionsService.route() and directionsDisplay.setDirections() when appropriate.
Putting all of this together, we have something like demonstrated in this phpfiddle.
1https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
I developed the following code to get the distance of the given 2 cities through 2 textfields and i want to send them to google maps distance matrix api using the following URl. I send those cities and got the JSON output file. but my problem is how can i get the specific attribute(distance) from that JSON file and display on a another textfield.
function m() {
var x = document.getElementById("autocomplete").value;
var y = document.getElementById("autocomplete1").value;
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + x + "&destinations=" + y + "&key=AIzaSyD5KX6VRon6yQ0vu4s6GSnAVzazRWg8wrc";
window.location=url; // this will go to the above url and display the JSON output file on the browser. I dont want that to be shown. just some processing and should display only the distance form that file on a textfield!
}
the JSON output file http://pastebin.ca/3318529
Please help to solve this. i am new to JSON. So if you have any other ideas tell me. Many thanks :)
If you use Javascript in Browser, you need use Google Maps Api.
Check this example:
<script src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function init() {
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: ['Los Angeles'],
destinations: ['New York'],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
alert(response.originAddresses[0] + ' --> ' + response.destinationAddresses[0] + ' ==> ' + response.rows[0].elements[0].distance.text);
}
});
}
</script>
<body onload="init()">
</body>
Running example https://jsfiddle.net/3b03m5mt/
You can check out this code
<?php
$addressFrom="Your from address";
$addressTo="your to address";
// Change address format
$formattedAddrFrom = str_replace(' ', '+', $addressFrom);
$formattedAddrTo = str_replace(' ', '+', $addressTo);
// Geocoding API request with start address
$distance_data = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins='.$formattedAddrFrom.'&destinations='.$formattedAddrTo.'&sensor=false&key=YOUR-API-KEY');
$output_data = json_decode($distance_data);
if(!empty($output_data->error_message)){
return $output_data->error_message;
}
//echo "<pre>";
//print_r($output_data) ;
$output_status = $output_data->status;
$output_km =$output_data->rows[0]->elements[0]->distance->text;
$output_meter =$output_data->rows[0]->elements[0]->distance->value;
?>
I am working on a Google Map which needs to show:
a KML (floor-plan)
a Polyline which should take its coordinates from a GET response, each 5 seconds.
I would like the polyline to update itself with the new coordinates that arrives from the RESTful API.
This is the code [updated]:
var FlightPath1 = []
$(document).ready(function() {
var BASE_URL = "https://its.navizon.com/api/v1/sites/" //Do not change this
SITE_ID = "1001" // Your site ID here
MAC_add = "00:1E:8F:92:D0:56" //Mac address of the device to track
USERNAME = "demo#navizon.com" // Your username
PASSWORD = "" // Your password
var Path1=new google.maps.Polyline({
path:FlightPath1,
strokeColor:"#F020FF",
strokeOpacity:0.8,
strokeWeight:2
});
// Send the request
jQuery.support.cors = true; // Enable cross-site scripting
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL + SITE_ID + "/stations/" + MAC_add + "/",
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
//Display the results
FlightPath1.push("new google.maps.LatLng(" + jimmi.loc.lat + "," + jimmi.loc.lng + "),");
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(jimmi.loc.lat,jimmi.loc.lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var SanDiegoKML = new google.maps.KmlLayer({
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/05w0kyw829_a.kml'
});
SanDiegoKML.setMap(map);
google.maps.event.addDomListener(window, 'load', jimmi);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000); //run the script each 5000 milliseconds
}
makeCall();
})
But I nothing happens. And I get no errors neither.
Could some one help me?
Thanks..
Two issues:
The necessary var, Path1 is internal and private to initialize(), therefore out of scope with regard to the ajax success function which is in an entirely different scope.
The ajax success function does nothing other than to push a string derived from the response onto an array. Doing so will not, in itself, affect the polyline.
Fix (1) first, then (2).