Javascript use onclick and geolocation to retrieve current location












0















I have to add a click handler to the button provided that will retrieve the users current location using the geolocation api.
Here's my code, I'm trying to use geolocation to set the current location of the user to the map but the button for some reasons does not work. Can anyone point out what I'm doing wrong and help me out?






<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
<style>
#mapid { height: 600px; }
</style>

<script>
const Mapping = {
map : null,
initializeMap : () => {
Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
subdomains: ['a','b','c']
}).addTo( Mapping.map );
},
resetLocation : ({lat,lon}) => {
Mapping.map.setView([lat,lon], 13);
}
}

window.onload = () => {
Mapping.initializeMap();

userCode();
}

function userCode() {
// JS CODE START
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
let pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};

Mapping.setPosition(pos);
Mapping.open(Mapping.map);
Mapping.map.setPosition(pos);
})
}

// JS CODE END

}

</script>
</head>
<body>

<!-- HTML CODE GOES HERE-->
<button onclick="userCode()">Get Location</button>

<div id="mapid" style="width: 600px; height: 400px;"></div>

</body>
</html>












share|improve this question





























    0















    I have to add a click handler to the button provided that will retrieve the users current location using the geolocation api.
    Here's my code, I'm trying to use geolocation to set the current location of the user to the map but the button for some reasons does not work. Can anyone point out what I'm doing wrong and help me out?






    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
    <style>
    #mapid { height: 600px; }
    </style>

    <script>
    const Mapping = {
    map : null,
    initializeMap : () => {
    Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
    L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: ['a','b','c']
    }).addTo( Mapping.map );
    },
    resetLocation : ({lat,lon}) => {
    Mapping.map.setView([lat,lon], 13);
    }
    }

    window.onload = () => {
    Mapping.initializeMap();

    userCode();
    }

    function userCode() {
    // JS CODE START
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
    let pos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
    };

    Mapping.setPosition(pos);
    Mapping.open(Mapping.map);
    Mapping.map.setPosition(pos);
    })
    }

    // JS CODE END

    }

    </script>
    </head>
    <body>

    <!-- HTML CODE GOES HERE-->
    <button onclick="userCode()">Get Location</button>

    <div id="mapid" style="width: 600px; height: 400px;"></div>

    </body>
    </html>












    share|improve this question



























      0












      0








      0








      I have to add a click handler to the button provided that will retrieve the users current location using the geolocation api.
      Here's my code, I'm trying to use geolocation to set the current location of the user to the map but the button for some reasons does not work. Can anyone point out what I'm doing wrong and help me out?






      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
      <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
      <style>
      #mapid { height: 600px; }
      </style>

      <script>
      const Mapping = {
      map : null,
      initializeMap : () => {
      Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
      L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: ['a','b','c']
      }).addTo( Mapping.map );
      },
      resetLocation : ({lat,lon}) => {
      Mapping.map.setView([lat,lon], 13);
      }
      }

      window.onload = () => {
      Mapping.initializeMap();

      userCode();
      }

      function userCode() {
      // JS CODE START
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
      let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
      };

      Mapping.setPosition(pos);
      Mapping.open(Mapping.map);
      Mapping.map.setPosition(pos);
      })
      }

      // JS CODE END

      }

      </script>
      </head>
      <body>

      <!-- HTML CODE GOES HERE-->
      <button onclick="userCode()">Get Location</button>

      <div id="mapid" style="width: 600px; height: 400px;"></div>

      </body>
      </html>












      share|improve this question
















      I have to add a click handler to the button provided that will retrieve the users current location using the geolocation api.
      Here's my code, I'm trying to use geolocation to set the current location of the user to the map but the button for some reasons does not work. Can anyone point out what I'm doing wrong and help me out?






      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
      <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
      <style>
      #mapid { height: 600px; }
      </style>

      <script>
      const Mapping = {
      map : null,
      initializeMap : () => {
      Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
      L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: ['a','b','c']
      }).addTo( Mapping.map );
      },
      resetLocation : ({lat,lon}) => {
      Mapping.map.setView([lat,lon], 13);
      }
      }

      window.onload = () => {
      Mapping.initializeMap();

      userCode();
      }

      function userCode() {
      // JS CODE START
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
      let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
      };

      Mapping.setPosition(pos);
      Mapping.open(Mapping.map);
      Mapping.map.setPosition(pos);
      })
      }

      // JS CODE END

      }

      </script>
      </head>
      <body>

      <!-- HTML CODE GOES HERE-->
      <button onclick="userCode()">Get Location</button>

      <div id="mapid" style="width: 600px; height: 400px;"></div>

      </body>
      </html>








      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
      <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
      <style>
      #mapid { height: 600px; }
      </style>

      <script>
      const Mapping = {
      map : null,
      initializeMap : () => {
      Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
      L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: ['a','b','c']
      }).addTo( Mapping.map );
      },
      resetLocation : ({lat,lon}) => {
      Mapping.map.setView([lat,lon], 13);
      }
      }

      window.onload = () => {
      Mapping.initializeMap();

      userCode();
      }

      function userCode() {
      // JS CODE START
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
      let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
      };

      Mapping.setPosition(pos);
      Mapping.open(Mapping.map);
      Mapping.map.setPosition(pos);
      })
      }

      // JS CODE END

      }

      </script>
      </head>
      <body>

      <!-- HTML CODE GOES HERE-->
      <button onclick="userCode()">Get Location</button>

      <div id="mapid" style="width: 600px; height: 400px;"></div>

      </body>
      </html>





      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>
      <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js" integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA==" crossorigin=""></script>
      <style>
      #mapid { height: 600px; }
      </style>

      <script>
      const Mapping = {
      map : null,
      initializeMap : () => {
      Mapping.map = L.map('mapid').setView([51.505, -0.09], 13);
      L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      subdomains: ['a','b','c']
      }).addTo( Mapping.map );
      },
      resetLocation : ({lat,lon}) => {
      Mapping.map.setView([lat,lon], 13);
      }
      }

      window.onload = () => {
      Mapping.initializeMap();

      userCode();
      }

      function userCode() {
      // JS CODE START
      if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
      let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
      };

      Mapping.setPosition(pos);
      Mapping.open(Mapping.map);
      Mapping.map.setPosition(pos);
      })
      }

      // JS CODE END

      }

      </script>
      </head>
      <body>

      <!-- HTML CODE GOES HERE-->
      <button onclick="userCode()">Get Location</button>

      <div id="mapid" style="width: 600px; height: 400px;"></div>

      </body>
      </html>






      javascript geolocation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 3:53









      hev1

      5,5783527




      5,5783527










      asked Nov 15 '18 at 3:47









      deceaseddddeceaseddd

      63




      63
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Use



          Mapping.resetLocation({lat:pos.lat,lon:pos.lng});


          Instead of



          Mapping.setPosition(pos);





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312138%2fjavascript-use-onclick-and-geolocation-to-retrieve-current-location%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Use



            Mapping.resetLocation({lat:pos.lat,lon:pos.lng});


            Instead of



            Mapping.setPosition(pos);





            share|improve this answer






























              0














              Use



              Mapping.resetLocation({lat:pos.lat,lon:pos.lng});


              Instead of



              Mapping.setPosition(pos);





              share|improve this answer




























                0












                0








                0







                Use



                Mapping.resetLocation({lat:pos.lat,lon:pos.lng});


                Instead of



                Mapping.setPosition(pos);





                share|improve this answer















                Use



                Mapping.resetLocation({lat:pos.lat,lon:pos.lng});


                Instead of



                Mapping.setPosition(pos);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 15 '18 at 6:49









                Shree

                12.4k2069121




                12.4k2069121










                answered Nov 15 '18 at 6:48









                Mohammad FaisalMohammad Faisal

                364




                364






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53312138%2fjavascript-use-onclick-and-geolocation-to-retrieve-current-location%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Xamarin.form Move up view when keyboard appear

                    JBPM : POST request for execute process go wrong