-2

I have to functions, one is within an external js file named "london.js" and one is within a HTML script.

I wish to take a value from the external file and insert it into my HTML script function.

   function initMap(cityLatLng) {
      map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: ldn,
}

  function loadLondon() {
      var ldn = {lat: 51.5, lng: -0.1}
}

I am not sure how to pass values through functions, I have tried putting the variable outside the function but it didn't work. I wish to make use of the var ldn in initMap.

Thanks in advance.

Overtime
  • 47
  • 10
  • pass it when you call it? unclear what you really want. – epascarello Mar 20 '18 at 14:02
  • 2
    I see *two* functions with no calls to either. Please edit your question to include a [mcve] – j08691 Mar 20 '18 at 14:02
  • Possible duplicate of [Javascript passing parameters to function](https://stackoverflow.com/questions/6638088/javascript-passing-parameters-to-function) – messerbill Mar 20 '18 at 14:03
  • Which one is your external? And which one is your embedded script? Do you have control over the external script? Are you able to make changes to it? – khollenbeck Mar 20 '18 at 14:08
  • @KrisHollenbeck initMap is internal and loadLondon is external, I am able to make changes to both, I just wish to make use of that variable within the other function – Overtime Mar 20 '18 at 14:11
  • @Overtime One option would be to create a global namespace via your external script. And then access your global function via your HTML file. Assuming your external script loads before your embedded script. https://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript And some other options worth looking into would be module loading, or using something like jQuery widget library. – khollenbeck Mar 20 '18 at 14:20

1 Answers1

2

An alternative is to return that variable ldn and assign it to the property center:

function initMap(cityLatLng) {
  map = new google.maps.Map(document.getElementById('map'), {
  zoom: 12,
  center: loadLondon(),
}

function loadLondon() {
  var ldn = {lat: 51.5, lng: -0.1};

  // your logic with ldn;

  return ldn;
}
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Although this sounds good in theory, the word `load` in the function makes me wonder if it's being loaded asynchronously, in which case, there is a lot more work to do. – Scott Sauyet Mar 20 '18 at 14:05
  • @Ele there are other functions that may need to fill 'center' with other coordinates, such as a function named loadCardiff in the external file – Overtime Mar 20 '18 at 14:28
  • Please add more code to understand the whole context. – Ele Mar 20 '18 at 14:48