功能在单击按钮之前运行

时间:2016-01-09 07:27:17

标签: javascript jquery click

我通过一键功能调用一系列函数,如下所示(从我的实际代码中简化)。问题是,initMap()在用户点击<button>之前正在运行,引发错误,因为latitude / longitude在用户输入地址之前未定义click()功能。

如何阻止initMap()click()功能之前运行?

$("button").click(function() {
  var user_search = $("input").val();
  var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + user_search + ".json?access_token=MYAPIKEY";
  $.getJSON(url, function(data) {
      var number = data.features[0].address;
      var route = data.features[0].text;
      var latitude = data.features[0].geometry.coordinates[1];
      var longitude = data.features[0].geometry.coordinates[0];
      initMap(latitude, longitude);
  });
});

var map;
var infowindow;

// Create Google Map with location at center

function initMap(latitude, longitude) {
  var location = {lat: latitude, lng: longitude};
  console.log(location);

  map = new google.maps.Map(document.getElementById('map'), {
    center: location,
    zoom: 15
  });

  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: location,
    radius: 3200,
    types: ['school']
  }, callback);
}

// List nearby places

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      listPlaces(results[i]);
    }
  }

  else {
    alert("There was an error finding address data.")
  }
}

// ONLY list places with characteristics below
function listPlaces(place) {
  if (place.name.indexOf('High ') > -1 && place.name.indexOf('Junior') == -1)  {
    $('body').append('<br>' + place.name);
  }
}

2 个答案:

答案 0 :(得分:0)

你的initMap函数没有正确关闭。错误是因为语法错误不是因为initMap()没有按钮点击运行

$("button").click(function() {
      initMap(latitude, longitude);
});

function initMap(latitude, longitude) {
     //do stuff
callback();
  } 

function callback(results, status) {
  //do stuff
}

function listPlaces(place) {
   //do more stuff
}

答案 1 :(得分:0)

这是您想要的真实代码吗?

$("button").click(function() {
      initMap(latitude, longitude);
});

function initMap(latitude, longitude) {
     //do stuff
}

function callback(results, status) {
  //do stuff
}

function listPlaces(place) {
   //do more stuff
}