-1

I'm quite new to coding.

Basically, I'm trying to use the below external JS file in my HTML but it doesn't work when I include this in my HTML file:

var map = L.map('map').setView([51.505, -0.09], 13);

L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox/satellite-v9',
    tileSize: 512,
    zoomOffset: -1,
    accessToken: 'pk.eyJ1IjoidGhhaWxlZSIsImEiOiJjbDFxYmUzZGwxZWFzM2lxcjJkOWNmZmlsIn0.B57x2tvc2UbNrR1jdV0nrg'
}).addTo(map);

But when I include these codes in the same script tag in HTML, it works? My html code below:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Map</title>
        <meta name="description" content="thai Yik Lee Portfolio">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin=""/>

        <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
    </head>

    <body>
        <h1>MAP</h1>
        <div id="map" style="height: 500px">
            Here
        </div>
        
        <script src="/libs/map.js" type="text/javascript"></script>
    </body>
</html>

Any help is appreciated, thank you!

2
  • Do you get any errors in your console? Commented Apr 8, 2022 at 12:31
  • @Grumpy, not there is no error in my code. When I run the js code directly in the script tag in the HTML, the map runs, but when I put the code externally in a separate JS file, my map does not load up. Commented Apr 8, 2022 at 14:20

1 Answer 1

0

Found the answer, the path to my file had an extra '/'

Sign up to request clarification or add additional context in comments.

1 Comment

Please mark this as solved. Also, you should do ./libs/map.js instead of libs/map.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.