0
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 2, 2016 at 22:56
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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());
    
answered Jan 2, 2016 at 23:20
\$\endgroup\$
3
\$\begingroup\$

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);
 }
});
answered Jan 4, 2016 at 20:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.