4

I am new to programming so don't judge me. Trying to write code to measure length with latitude and longitude. It's showing this error:

length.html:27 Uncaught ReferenceError: area is not defined at HTMLInputElement.onclick (length.html:27)

<html>
    <head></head>
    <body>
        <script type="module">
                import LatLon from 'https://cdn.jsdelivr.net/npm/geodesy@2.2.0/latlon-spherical.min.js';
                function area()
                {
                var la1 = document.getElementById(lat1).value;
                var la2 = document.getElementById(lat2).value;
                var lo1 = document.getElementById(lon1).value;
                var lo2 = document.getElementById(lon2).value;
                const p1 = new LatLon(la1, lo1);
                const p2 = new LatLon(la2, la2);
                const d = p1.distanceTo(p2);
                    document.write('<br>Length is : ' + d);
                }
        </script>
        <form>
            First point<br>
             Latitude:&nbsp;
             <input type="text" name="lat1" id="lat1"><br>
             Longitude:
            <input type="text" name="lon1" id="lon1"><br>
            Second point<br>
            Latitude<input type="text" name="lat2" id="lat2"><br>
            Longitude<input type="text" name="lon2" id="lon2"><br>
            <input type="button" value="submit" onclick="area()">
        </form>
    </body>
</html>
theduck
  • 2,589
  • 13
  • 17
  • 23
  • write your function just before your body tag ends – ANIK ISLAM SHOJIB Sep 15 '19 at 09:56
  • See the answers to the linked question. Basically, the function you call from an `onxyz`-attribute-style event handler must be a global, but your `area` isn't a global because your script is a *module*, and top-level declarations in modules aren't globals (they're only accessible within the module). Instead, use modern techniques to hook up you handler: Get the element reference, and then use `addEventListener`. – T.J. Crowder Sep 15 '19 at 10:00
  • Your script is loaded before the rest of the page. Search for "How HTML is loaded", or "Where to put script tag", or look at this answer - –  Sep 15 '19 at 10:01
  • @AndrewShymanel - Modules are automatically deferred (in effect), see [here](https://html.spec.whatwg.org/multipage/scripting.html#the-script-element) and scroll down a bit to the graphic showing when and how scripts are loaded and executed. – T.J. Crowder Sep 15 '19 at 10:02
  • 1
    @T.J.Crowder you're totally right, thanks –  Sep 15 '19 at 10:09

1 Answers1

3

When you use <script type="module">, a separate scope is created to prevent name collisions. See JavaScript modules for more details.

You can make your function global by adding it to the window namespace, like so:

window.area = area;

Or you could simply use addEventListener in your JavaScript:

document.querySelector('[type=submit]').addEventListener('click', area);

JoshG
  • 6,472
  • 2
  • 38
  • 61