Reputation: 663
I am making an app based on Google maps. Now the user enters some locations. I want to create a link which has all the locations entered by the user. The user has a limit of 10 locations.
Now i want to create a dynamically to request Google for distances between that locations. How to create the link dynimacally when i don't know how many locations has user entered.
here is the basic link for two locations in Google's documentation:
which gives:
Vancouver to San Francisco Vancouver to Victoria Seattle to San Francisco Seattle to Victoria
now if i have many inputs, how to create this link dynamically using javascript ?
thanks regards.
Upvotes: 1
Views: 117
Reputation: 5390
You may find it easier to use the distanceMatrix class from the google maps api which takes js object and handles the request passing the result to a callback.
modified version of google example:
var origins = ["Vancouver BC", "Seattle"];
var destinations = ["San Francisco", "Victoria BC"];
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origins],
destinations: [destinations],
travelMode: google.maps.TravelMode.BICYCLING,
}, callback);
function callback(response, status) {
// Response contains the same object as the one from the link
}
https://developers.google.com/maps/documentation/javascript/distancematrix
Upvotes: 1
Reputation: 72967
The url parameters seem to consist of the following elements:
// Url,
# http://maps.googleapis.com/maps/api/distancematrix/json?
// Origin locations:
# origins=Vancouver+BC|Seattle
// Destinations:
# &destinations=San+Francisco|Victoria+BC
// (And some additional options:)
# &mode=bicycling
# &language=fr-FR
# &sensor=false
Now, if you have 2 arrays with locations, the url is pretty simple to build:
var origins = ["Vancouver BC", "Seattle"];
var destinations = ["San Francisco", "Victoria BC"];
var url = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
origins.join('|').replace(/ /g,'+') +
"&destinations=" +
destinations.join('|').replace(/ /g,'+') +
"&mode=bicycling&language=fr-FR&sensor=false";
.join('|')
joins the array elements together with a pipeline (|
) character in between, so origins.join('|')
returns "Vancouver BC|Seattle"
.
Then, .replace(/ /g,'+')
replaces all spaces in the string with plus (+
) signs.
You can add as many locations as you want to these arrays.
Upvotes: 0