I am making an HTTP request with the Google Maps API and I have to pass in parameters (adresses/coordinates):
$.ajax({
url : 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + $("#origin").val() + '&destinations=' + $("#destinations").val() +'&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0',
type: 'GET',
success : function(data){
//My code
}
});
I was wondering if there was any better cleaner way to do this. I know string concatenation is an option, but I want to know if I have any other options. I just feel like I'm doing this wrong.
2 Answers 2
If we examine the official docs, we can conclude that what you have is standard and clean. Mostly. I'll say a few things though:
Instead of the
success
key, you could choose to use.done()
, as in:$.ajax({ // parameters }) .done(function( data ) { // success });
To evade string concatenation, you could use a custom string formatting function. JavaScript doesn't have a string format method, so you'll have to add one in, like this one. Then you can code like this:
var mapsURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0';
then
url: mapsURL.format($("#origin").val(), $("#destinations").val());
You may want to put your query string into the data property of your XHR request in order to clean up your request as well.
$.ajax({
url: "https://maps.googleapis.com/maps/api/distancematrix/json",
type: "GET",
data: {
origins: $("#origin").val(),
destination: $("#destinations").val(),
mode: "driving",
key: "AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0"
},
success: function(data) {
console.log(data);
}
});