Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisgrim's avatar

Using JS to get JSON for lat and long

Hi, I am getting a users lat and long from google when they submit an address using the autocomplete api. I am trying to take it one step further by catching anyone who submitted an address without using the autocomplete and submitting their address to google to get the lat and long back. I have figured out how to check if they used the autocomplete by checking if latitude was filled in, but I am struggling with the else part to submit the address to google and receive the json. My check() function looks like this:

function check() {
let latitude = document.getElementById("latitude").value;
let term = document.getElementById("getaddy").value;
  if (latitude) {
    window.prompt("It passed", "");
  } else {
    window.open('https://maps.googleapis.com/maps/api/geocode/json?address='+term+'&key=AIzaSyCN5Ms4IMOqwpVhca6ceY8iHSLqAUF_j0I', '_blank');
    return true;
  }
}

When I enter an addy without autocomplete it pops up a page showing the google info about that address. How do I get that information and apply it to the element with id latitude, then submit my form with that info? I was trying function getJSONP(url, success) but I was getting an unexpected string error when I entered the address into url.

Thank so much Chris

0 likes
4 replies
Cronix's avatar
Cronix
Best Answer
Level 67

make an ajax get request instead of window.open. Then you can receive the data in the success event of the ajax call instead of having it "go to the screen". It will just send back json that you can parse through to get whatever data you're needing from it.

Like to access the lat/lng from the success event if the ajax call, you'd just

let term = $("#getaddy").val();

$.ajax({
    url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) + '&key=yourkey',
    type: 'get',
    success: function(data) {
        if (data.status === 'OK') {
            // Get the lat/lng from the response
            let lat = data.results[0].geometry.location.lat;
            let lng = data.results[0].geometry.location.lng;

            // now do something with the data you got back
        }
    },
    error: function(msg) {
        // handle error
    }
});

I assume you're using jquery since you mentioned getJSONP, so I wrote the above with jquery.

PS Now get yourself a new maps api key! This one is no longer any good since it was posted on a public forum. You don't want someone else using it and charging it to your account... Be careful about posting private keys in public.

chrisgrim's avatar

Hi @Cronix, First off thank you so much! Your answer totally worked! And yes, I for some reason stupidly put the api key. I will have to change it asap!

I can ask a new question but I am having an issue adding the lat and lng variables to my html form.

I tried adding

document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lng;

What I am guessing is that it may be too late to add them to my current submission? Do I need to submit a new form submission from within that ajax response?

Cronix's avatar

You didn't show any of that code, so I'll show you pseudocode

$(function() {

    $('#your-form').on('submit', function(e) {
        e.preventDefault();

        let term = $("#getaddy").val();
        let $form = $(this);

        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) + '&key=yourkey',
            type: 'get',
             success: function(data) {
                if (data.status === 'OK') {
                    // Get the lat/lng from the response
                    let lat = data.results[0].geometry.location.lat;
                    let lng = data.results[0].geometry.location.lng;

                     // now do something with the data you got back
                     // assign lat/lng to form input values
                     $('#latitude').val(lat);
                     $('#longitude').val(lng);
                     // submit the form
                     $form.submit();
                }
            },
            error: function(msg) {
                // handle error
            }
        });

    });
});

That assumes you have a form with the id of my-form, and inputs with ids of latitude/longitude in the form. Everything else is the same as my original code. The form will not submit unless a lat/lng was found. If you want it otherwise, adjust how you need.

Just a note... if you're using jQuery, then use jQuery. It will simplify your code. These are the same thing, but shorter than vanilla js. I mean if you're already using it, take advantage of it.

// document.getElementById("latitude").value = lat;
$('#latitude').val(lat);
// document.getElementById("longitude").value = lng;
$('#longitude').val(lng);

etc

chrisgrim's avatar

That I tried to add that but it isnt working. I figured I should show the whole code to be clear. Here is my JS

function check() {
let latitude = document.getElementById("latitude").value;

 if (latitude) {
    window.prompt("It passed", "");

  } else {

$(function() {

    $('#my-form').on('submit', function(e) {
        e.preventDefault();

        let term = $("#getaddy").val();
        let $form = $(this);

        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) +'&key=AIzaSyDGz4sPbdoal_aGfh6tEET5iWpGnLXOmmM',
            type: 'get',
             success: function(data) {
                if (data.status === 'OK') {
                    // Get the lat/lng from the response
                    let lat = data.results[0].geometry.location.lat;
                    let lng = data.results[0].geometry.location.lng;

                     // now do something with the data you got back
                     // assign lat/lng to form input values
                     $('#latitude').val(lat);
                     $('#longitude').val(lng);
                     // submit the form
                     $form.submit();
                }
            },
            error: function(msg) {
                
            }
        });

    });
});

window.prompt("It failed", "");

 //    return true;
}
}

And here is my html

<form method="GET" id="my-form" action="/search" onsubmit="check()">
                    <div class="md-form">
                        <input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
                        <input id="latitude" type="hidden" name="latitude">
                        <input id="longitude" type="hidden" name="longitude">
</div>
                </form>

This whole setup is to catch anyone who doesn't use the autocomplete. If on submit I don't see a lat( because they didn't use autocomplete), I am trying to get the lat and lng anyways. Thanks so much @Cronix

Please or to participate in this conversation.