如何在Javascript中的函数内访问变量内的变量?

时间:2018-04-04 17:41:30

标签: javascript ruby-on-rails google-maps

我需要通过在单击按钮时将x指定给lat对象来更改map函数中的center值。但是,我似乎无法弄清楚如何从我的alertFunction分配map.center.lat = 43.138428。本质上,我问的是如何在一个对象内部,一个函数内部,从另一个函数引用一个对象。我在Rails里面工作。

<script>
//function to update my center
function alertFunction() {
    var x = document.getElementById("myInput").value;
    initMap();
    **Wrong Code**
    **// map.center.lat = 43.138428;**
};

//function to start map
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center:{lat: 41.138428, lng:-85.140239},
    });

3 个答案:

答案 0 :(得分:2)

您的initMap函数应该返回一些内容,或者您​​可以使用参数来设置.lat

// the latter
function alertFunction() {
    var x = document.getElementById("myInput").value;
    initMap(43.138428);
    //      ^ pass latitude value
};

//function to start map
function initMap(latitude) {
//               ^ parameter
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center:{lat: latitude, lng:-85.140239},
      //           ^ from parameter
  });
}

// the former
function alertFunction() {
    var x = document.getElementById("myInput").value;
    var map = initMap();
    //        ^ initMap returns the map
    map.center.lat = 43.138428;
};

//function to start map
function initMap(latitude) {
 return new google.maps.Map(document.getElementById('map'), {
   zoom: 10,
   center:{lat: latitude, lng:-85.140239},
 });
}

答案 1 :(得分:0)

<script>
//function to update my center
function alertFunction() {
    var x = document.getElementById("myInput").value;
    var map = initMap();
    **Wrong Code**
    **// map.center.lat = 43.138428;**
};

//function to start map
  function initMap() {
    return map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center:{lat: 41.138428, lng:-85.140239},
    });

retrun map或者您必须使用全局变量。

答案 2 :(得分:0)

在他们展示的谷歌地图文档中 - 您需要声明您的地图&#39;函数之外的变量或其他函数无法访问它。

didFinishLaunchingWithOptions

这样你的initMap()就会改变initMap函数之外的变量。

相关问题