Call google map function in javascript from java code - javascript

Basically I want to use the Test.java to call the initMap method from index.js, in order to get the shortest distance from originlist to the destination.
However, when I run the Test.class,
it shows ReferenceError: "Google" is not defined in <eval> at line number 10.
The line is var bounds = new google.maps.LatLngBounds;
public class Test {
public static void main(String []args) throws ScriptException, IOException, NoSuchMethodException {
String[] addres = new String[3];
call("Airport Blvd, Singapore",new String[]{"50 Nanyang Ave, 639798 Singapore","21 Lower Kent Ridge Rd, 119077, Singapore","81 Victoria St, Singapore"});
}
public static void call(String s, String [] sarr)throws ScriptException, IOException, NoSuchMethodException{
StringBuilder sb = new StringBuilder();
sb.append(s+"*");
for(String element:sarr){
sb.append(element + "*");
}
System.out.println(sb.toString().substring(0, sb.toString().length()-1));
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("/Projects/GetShortestDistance/index.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
System.out.println("Testing:"+ inv.invokeFunction("initMap", sb.toString()));
}
}
Here is my javascript refer to the Google Developer
function initMap(longstr) {
var bounds = new google.maps.LatLngBounds;
var markersArray = [];
// longstr ='Airport Blvd, Singapore*21 Lower Kent Ridge Rd, 119077, Singapore*50 Nanyang Ave, 639798 Singapore*80 Mandai Lake Rd, 729826*551 bukit timah road'
var array = longstr.split('*');
var destination = array[0];
var origins1 = [];
for(var i =1; i<array.length;i++){
origins1.push(array[i]);
}
var min = "";
var minAddress = null;
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: 55.53, lng: 9.4},
zoom: 10
});
var geocoder = new google.maps.Geocoder;
var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
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 {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
deleteMarkers(markersArray);
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>';
if(min > parseFloat(results[j].duration.text.slice(0, -5))){
min = parseFloat(results[j].duration.text.slice(0, -5));
minAddress = originList[i];
}
}
}
}
});
return longstr;
}
function deleteMarkers(markersArray) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
The js works fine in index.html which are able to show the distance and map.

Related

Extract element from function result in javascript

I'm trying to get the value from the element(?) named 'price' in this block of code into another script to use as the amount to charge on a custom Stripe Checkout page.
function CalculatedRecommendedDistance() {
CalculateDistanceforAllAlternativeRoutes();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
//Convert driving distance to price
document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
// The value that this statement produces is what I need ==> parseFloat(document.getElementById("price").innerHTML);
}
}
});
}
Or more specifically, the value that this statement produces:
parseFloat(document.getElementById("price").innerHTML);
I've tried putting the following, and many variations besides, in the same script to create a variable, but the result returned in the console is always either NaN or undefined.
var solution = document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
Here's the full script:
<script>
var booking_fee = 0.50;
var base_fare = 1.50;
var rate_per_km = 1.30;
var outputDiv = document.getElementById('output');
var text = '3.14someRandomStuff';
var placeSearch, originautocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
originautocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */
(document.getElementById('pick_up_address')), {
types: ['geocode']
});
// Set initial restrict to the greater list of countries.
originautocomplete.setComponentRestrictions({
'country': ['nz']
});
destinationautocomplete = new google.maps.places.Autocomplete(
(document.getElementById('drop_off_address')), {
types: ['geocode']
});
destinationautocomplete.setComponentRestrictions({
'country': ['nz']
});
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
function CalculatedRecommendedDistance() {
CalculateDistanceforAllAlternativeRoutes();
var origin = document.getElementById('pick_up_address').value;
var destination = document.getElementById('drop_off_address').value;
var geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false,
avoidFerries: false
}, function(response, status) {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var outputDiv = document.getElementById('outputRecommended');
outputDiv.innerHTML = '';
//Display distance recommended value
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + ' in ' +
results[j].duration.text + '<br>';
//Convert driving distance to price
document.getElementById("price").innerHTML = booking_fee + base_fare + (rate_per_km * parseFloat(results[j].distance.text));
// The value that this statement produces is what I need ==> parseFloat(document.getElementById("price").innerHTML);
}
}
});
}
function CalculateDistanceforAllAlternativeRoutes() {
var directionsService = new google.maps.DirectionsService();
var start = document.getElementById('pick_up_address').value;
var end = document.getElementById('drop_off_address').value;
var method = 'DRIVING';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode[method],
provideRouteAlternatives: true,
unitSystem: google.maps.UnitSystem.METRIC,
optimizeWaypoints: true
};
directionsService.route(request, function(response, status) {
var routes = response.routes;
var distances = [];
for (var i = 0; i < routes.length; i++) {
var distance = 0;
for (j = 0; j < routes[i].legs.length; j++) {
distance = parseInt(routes[i].legs[j].distance.value) + parseInt(distance);
//for each 'leg'(route between two waypoints) we get the distance and add it to
}
//Convert into kilometer
distances.push(distance / 1000);
}
var maxDistance = distances.sort(function(a, b) {
return a - b;
});
//Display distance having highest value.
outputDiv.innerHTML = Math.round(maxDistance[routes.length - 1]) + " KM";
});
}
</script>
Many thanks for any help you're able to provide.

JS global variable reseting when js function is called from C#

I create some markers on a google Map. I call the create marker function from c#
for(int a = 0; a<cpt;a++)
{
jsFunc = "myglobalObject.createMarker(" + nearestStations[a][0] + "," + HttpUtility.JavaScriptStringEncode("test", true) + ")";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "script" + a, "$(function () {" + jsFunc + "; });", true);
}
My js looks like this :
var markers = [];
var infoWindowIsSet = false;
myglobalObject = {
map: false,
prev_infowindow: false,
initializeMap: function () {
$(document).ready(function () {
var adresseConnexion = document.getElementById("tbAdresseDefault").value;
var geocoder = new google.maps.Geocoder();
mapOptions = {
zoom: 6,
center: { lat: 46, lng: 1 },
language: "en-US",
mapTypeId: google.maps.MapTypeId.ROADMAP
}
myglobalObject.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
geocoder.geocode({ 'address': adresseConnexion }, function (results, status) {
if (status == 'OK') {
myglobalObject.map.setCenter(results[0].geometry.location);
myglobalObject.createMarker(results[0].geometry.location, "test");
console.log(results[0].geometry.location);
} else {
alert('Adresse incorrecte ');
}
});
});
},
createMarker: function (position, information) {
marker = new google.maps.Marker({
position: position,
map: myglobalObject.map,
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow = new google.maps.InfoWindow({ content: information });
if (myglobalObject.prev_infowindow) {
myglobalObject.prev_infowindow.close();
}
myglobalObject.prev_infowindow = infowindow;
infowindow.open(myglobalObject.map, this);
infoWindowIsSet = true;
});
google.maps.event.addListener(myglobalObject.map, "click", function () {
if (infoWindowIsSet)
infowindow.close();
});
return marker;
}
}
As you can see, I have a map variable in "myglobalObject" that I set here :
myglobalObject.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
However, after calling the createrMarker func from C#, the variable map seems to be reseted to "false" so the parts where I need it in createMarker are failing. I tried to put map as a global variable and it still failed. What could I do ?
The .cs code :
public string[][] nearestStations = new String[100][];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
parsingXMLDistance();
}
public void parsingXMLDistance()
{
double latOfYourStation = double.Parse(GetLatLng(tbAdresseDefault.Text)[0], CultureInfo.InvariantCulture);
double lngOfYourStation = double.Parse(GetLatLng(tbAdresseDefault.Text)[1], CultureInfo.InvariantCulture);
string latStr, lngStr;
int cpt = 0;
for (int j = 0; j < 100; j++)
nearestStations[j] = new String[1];
string jsFunc;
PDV.pdv_liste l = new PDV.pdv_liste();
l = (litXMLListe("myXMLFile"));
for (int i = 0; i <l.pdv.Length; i++)
{
System.Diagnostics.Debug.Write(i + "\r\n");
if (l.pdv[i].latitude != "" && l.pdv[i].longitude != "") {
if (DistanceTo(latOfYourStation, lngOfYourStation, double.Parse(l.pdv[i].latitude, CultureInfo.InvariantCulture) / 100000, double.Parse(l.pdv[i].longitude, CultureInfo.InvariantCulture) / 100000) < double.Parse(tbDistDefault.Text, CultureInfo.InvariantCulture) )
{
latStr = "" + double.Parse(l.pdv[i].latitude, CultureInfo.InvariantCulture) / 100000;
lngStr = "" + double.Parse(l.pdv[i].longitude, CultureInfo.InvariantCulture) / 100000;
latStr = latStr.Replace(',', '.');
lngStr = lngStr.Replace(',', '.');
nearestStations[cpt][0] = "{lat:" + latStr + ",lng:" + lngStr + "}";
cpt++;
}
}
}
for(int a = 0; a<cpt;a++)
{
jsFunc = "myglobalObject.createMarker(" + nearestStations[a][0] + "," + HttpUtility.JavaScriptStringEncode("test", true) + ")";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "script" + a, "$(function () {" + jsFunc + "; });", true);
}
}

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>

Google geocoder service is not returning appropriate lat and long values with javascript

Google map is not showing the exact location. I'm taking the address from our clients and will display them the map. I cross checked the google lat and long with mine, it is not returning the exact values. Here is my code, if I am wrong, please guide me.
function callMap() {
var fullAddress = address + "," + city + "," + state + "," + zip;
var lat_Company = "";
var lng_Company = "";
geocoder.geocode({
'address': fullAddress
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat_Company = parseFloat(results[0].geometry.location.lat());
lng_Company = parseFloat(results[0].geometry.location.lng());
var lCompanyObject = new Object();
lCompanyObject.Name = companyDetails.CompanyName;
lCompanyObject.Description = address + "<br/>" + city + ", " + state + "," + zip;
lCompanyObject.FullAddress = address + ", " + city + ", " + state + "," + zip;
lCompanyObject.Lat = lat_Company;
lCompanyObject.Lng = lng_Company;
displayCompany(city, state, "comp_map", "mapinfowindow", lCompanyObject, "fromSideBar");
}
});
var abpoutsideBarBuilder = '<ul>' +
'<li><div id="map_wrapper1">' +
'<div id="comp_map1"></div>' +
'<div id="mapinfowindow"style="display:none" ><b>#name</b><br>#description</div></div></li></ul>';
$('.about_map_addr_businesshours').html(abpoutsideBarBuilder);
}
function displayCompany(pCity, pState, pMapDiv, mapinfowindow, lCompany, from) {
var requestLocation = lCompany.FullAddress;
geocoder.geocode({
'address': requestLocation
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = parseFloat(results[0].geometry.location.lat());
var lng = parseFloat(results[0].geometry.location.lng());
if (lat != null && lng != null) {
centerLat = lat;
centerLng = lng;
initDisplayMap(centerLat, centerLng, pMapDiv, mapinfowindow, lCompany, from);
}
} else {
console.error("Geocode was not successful for the following reason ::" + status);
}
});
}
function initDisplayMap(pCenterLat, pCenterLng, pMapDiv, mapinfowindow, pCompany, from) {
if ($("#" + mapinfowindow).length > 0) {
var latlng = new google.maps.LatLng(pCenterLat, pCenterLng);
var myOptions = {
zoom: 14,
center: latlng,
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(pMapDiv), myOptions);
var infowindow = null;
infowindow = new google.maps.InfoWindow({});
var LatLngList = new Array();
var marker = pCompany;
var markerHTML = $('#mapinfowindow').clone().html();
if (from.indexOf("fromSideBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
} else if (from.indexOf("fromAboutBar") != -1) {
markerHTML = markerHTML.replace("#name", marker.Name);
markerHTML = markerHTML.replace("#description", marker.Description);
}
if (marker.Lat != null && marker.Lng != null) {
var myLatLng = new google.maps.LatLng(marker.Lat, marker.Lng);
LatLngList[LatLngList.length] = myLatLng;
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
clickable: true,
html: markerHTML
});
google.maps.event.addListener(beachMarker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
var bounds = new google.maps.LatLngBounds();
if (LatLngList.length > 1) {
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
//Fit these bounds to the map
map.fitBounds(bounds);
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(beachMarker.getPosition());
}
}
}
}
Don't mix up geocoder an places.
Nakedcherry Waxing Boutique 6th Street Parkhurst,South Africa
the bold part of this string obviously isn't a address-component.
Expecting the desired result is as when I would expect to get my location for a query like
Dr.Molle,Berlin,Germany
The result you get by the geocoder is for 6th Street Parkhurst,South Africa, and the result is correct.
When you look for a place use the places-textsearch, the result for the given query will be: -26.1437060,28.0207660

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]

Categories

Resources