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;
?>
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'm Trying to build an app with Cordova. With the app you should take pictures, these pictures needs to be uploaded to a database together with the location where the picture is taken.
The app on default shows a x number of the most nearest taken pictures to your live location.
Beneath here i post the javascript code i have right now, most of the code is from Cordova self. Is it better to modify this code or start over?
I can now access the camera and take a picture, but how do i upload this picture together with the location to a database?
And how can load the nearest pictures from the database?
var Latitude = undefined;
var Longitude = undefined;
window.onload = function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){
navigator.notification.alert("ready");
document.getElementById("camera").addEventListener
("click", cameraTakePicture);
}
function cameraTakePicture() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData, imageURI) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
getLocation();
navigator.notification.alert(image.src);
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
function getLocation() {
navigator.notification.alert("start locatie");
navigator.geolocation.getCurrentPosition(onPicturesSuccess, onPicturesError, { enableHighAccuracy: true });
}
var onPicturesSuccess = function (position) {
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getPictures(Latitude, Longitude);
}
function getPictures(latitude, longitude) {
//Load pictures which are the nearest
}
var onPicturesWatchSuccess = function (position) {
var updatedLatitude = position.coords.latitude;
var updatedLongitude = position.coords.longitude;
if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
Latitude = updatedLatitude;
Longitude = updatedLongitude;
getPictures(updatedLatitude, updatedLongitude);
}
}
// Error callback
function onPicturesError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Watch your changing position
function watchPicturePosition() {
return navigator.geolocation.watchPosition
(onPicturesWatchSuccess, onPicturesError, { enableHighAccuracy: true });
}
You can use Cordova File Transfer Plugin to upload your photos to your backend service (DB). In FT Plugin you can add some additional headers, or properties e.g. LAT and LON properties.
Since you didn't specifically mention it, I'm going to assume you have access to jQuery inside your Cordova app.
Inside your onSuccess you have to make an AJAX call that submits the image and location to your PHP server. Below is an example:
var request = {
'url': 'path/to/your/php/script.php',
'method': 'POST',
'data': {
'image': image.src,
'location': getLocation()
}
}
$.ajax(request).done(function(response) {
// request is done
});
Your PHP server script will have to take the incoming data and save it to your database.
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]}`)
I refer to the question Polygon "Drawing and Getting Coordinates with Google Map API v3" and the code by jhawes which works fine; BUT I've struggle to post the lat/lng-values to a DB using php.
In other scripts with single coordinates I use the following (whereas the variables "BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng" are of no interest for that question):
function saveData(BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng) {
var latlng = marker.getPosition();
window.location.href = "schritt_2.php?lat=" + latlng.lat() +
"&lng=" + latlng.lng() + "&MTBNr=" + BlattNr + "&Quadrant=" + Quadrant + "&MTBlat=" + MTBlat + "&MTBlng=" + MTBlng + "&Qmlat=" + Qmlat + "&Qmlng=" + Qmlng;
marker.setMap(null);
}
With this I can post the lat and lng of the single point coordinate - but how to pass the multiple lat and lng of various points? I don't know how to define the variable and how to construct the "saveData" function...
Many thanks in advance for any help :-)
Okay, I copy/pasted the code that jhawes put in jsFiddle
I added a few things.
add jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Save_data
function save_data() {
var data = [];
var len = myPolygon.getPath().getLength();
for (var i = 0; i < len; i++) {
data.push([myPolygon.getPath().getAt(i).lat(), myPolygon.getPath().getAt(i).lng()]);
}
// send data to the server
$.ajax({
url: 'save.php?p=' + JSON.stringify(data),
success: function (message) {
$('#ajaxresponse').html(message);
}
});
}
A button and a display div. Put them somewhere at the bottom of the markup.
<input type="button" onclick="save_data()" value="SAVE">
<div id="ajaxresponse"></div>
Server side: I don't do much here; I'm sure you can handle it.
save.php
<?php
if (isset($_GET['p'])) {
$locations = json_decode($_GET['p'], true);
echo print_r($locations, true) . '<br>';
echo "let's print the second point: lat=" . $locations[1][0] . ", lng=" . $locations[1][0];
}
?>
For a website where a user enters his address, I'm trying to find the location closest to him where the user can collect the ordered goods.
Based on the user's address I can narrow down the possible pick up locations to between 2 and 5. So I'd like to calculate the distance between user's address (point A) and the possible pick up locations.
The demo here works fine with just two addresses. I've adapted the code as much as I can to work with more than two addresses. I posted my JS code here since I can't seem to properly format it in SO.
In the code are two alerts. The first alert correctly shows the different pick up locations. But the second alert always shows the LAST pickup location.
Can anyone explain why?
HTML:
<p id="hello">Hello World</p>
JavaScript:
var geocoder, location1, location2, gDir;
function initialize(counter) {
if( counter == 0 ){
geocoder = new GClientGeocoder();
gDir = new GDirections();
}
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
$("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');
});
}
function getDistance(agency_add, counter) {
initialize(counter);
geocoder.getLocations(agency_add, function (response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode the address" + agency_add);
}
else {
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
//alert("ONE: "+location1.address);
geocoder.getLocations(document.forms[0].address1.value, function (response) {
//alert("TWO: "+location1.address);
if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
else {
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
$(document).ready(function(){
//put each agency address in an array
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
for (var i = 0; i < agencies.length; i++){
var res = getDistance(agencies[i], i);
}
});
you are calling geocoder.getLocations inside a loop. geocoder.getLocations runs asynchronously. when it receives the 2nd request while still processing the first, it cancels the first request.
If you want to multi-thread geocoder.getLocations you need to create multiple instances of it.