0

How can I return the name of the city to show on html page?

My function

function getCity(latitude, longitude){

var geocoder;
geocoder = new google.maps.Geocoder(); 
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
    {'latLng': latlng}, 
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    alert("city name is: " + city);
                    return city;
                }
        }

    }
);

The alert is working fine.

In HTML I called this function like that:

 <script> getCity("<%= map.latitude %>","<%= map.longitude %>")</script>

Tks in advance.

S_A
  • 411
  • 1
  • 7
  • 25

3 Answers3

0

Change your code to:

<script> document.write(getCity("<%= map.latitude %>","<%= map.longitude %>"))</script>

It will write into the document what your Javascript function returns.

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
  • It is returning "undefined" – S_A Aug 01 '16 at 20:17
  • `document.write` displays the value returned by the call to `getCity`. If it displays null, then there is something wrong in the function code. You need to debug to find out where the problem is. – Jocelyn Aug 02 '16 at 06:31
0

Create a DIV in your HTML, like this:

<div id="cityName"></div>

And in the javascript, replace the "alert" with this code:

document.getElementById("cityName").innerHTML(city);
Daniel Barral
  • 3,896
  • 2
  • 35
  • 47
0

If the alert works fine that means returned value is true. Then u can just call the function that returns the city name anywhere in the document body. Alternatively since the function only returns a string, u just need to assign it to a new variable and add more information to the returned function city string.

Like**function city () Return a city name value.

then var cityname = city() + 'more information';

**

apexpals.com
  • 305
  • 1
  • 11