2016-08-01 65 views
0

如何返回要显示在html页面上的城市名称?如何获取函数返回

我的功能

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; 
       } 
     } 

    } 
); 

警报工作正常。

在HTML我调用此函数那样:

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

韩国社交协会提前。

+0

'geocode'是一个异步调用。 – Marty

回答

0

你的代码更改为:

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

将会写入到文件你的JavaScript函数返回。

+0

它返回“undefined” –

+0

'document.write'显示调用返回到'getCity'的值。如果显示为空,则功能代码中出现错误。您需要进行调试才能找出问题所在。 – Jocelyn

0

在你的HTML创建一个DIV,像这样:

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

而在JavaScript中,使用此代码替换 “警报”:

document.getElementById("cityName").innerHTML(city); 
0

如果警报工作正常手段返回价值是真的。 然后你可以调用返回城市名称在文档主体任何位置的函数。 或者,因为该函数只返回一个字符串,你只需要将它分配给一个新的变量,并添加更多的信息到返回的功能城市字符串。

赞**功能城市() 返回城市名称值。

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

**

+0

希望它有帮助。请参考您的原始功能代码来应用它。 – Zuckerberg

相关问题