0

I have a code which is pick the current location and I set 2 cookies to store the latitude and longitude for later use, then I have second code to show this locations on map from the cookies stored.

I have tried to get some info on Google but it did not work. The way to insert my variables on code is not correct and I could not find a suitable solution to do it

on the line coords:{lat:37.128285,lng:-8.539157}, on the place of the latitude and longitude I want to place my variables I have try to do something like this but seems my syntax is not correct

center:{lat:}+ lati +{,lng:} + longi

I have also try like this but get an error

center:{lat:lati,lng:longi}

InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: not a number

This is my code to get the current location

<html>
    <body>

    <p>Click to get your current coordinates.</p>

    <button id="clickButton" onclick="getLocation()">Get Your Current Location and after refresh this page...</button>

    <p id="demo"></p>

    <script>
    setInterval(function(){ 
    //this code runs every second
    document.getElementById('clickButton').click(); 
    }, 1000);

    var x = document.getElementById("demo");

    function getLocation() {
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
    }
    }

    function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
    document.cookie = "Long = " + position.coords.longitude;
    document.cookie = "Lat = " + position.coords.latitude;
  
    document.cookie = "Longitude = " + position.coords.Longitude;
    }
    </script>

    </body>
    </html>

this my code to show the marks on map In this code I try to set 2 variables with my cookie value and then get implement on my code, but not in correct way on the line coords:{lat:${lati},lng:${longi}},

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Google Map</title>
    <style>
    #map{
      height:400px;
      width:100%;
    }
    </style>
    </head>
    <body>
    <h1>My Google Map</h1>
    <div id="map"></div>
    <script>
    var lati = getCookie("lat");
    var longi = getCookie("long");
    function initMap(){
      // Map options
      var options = {
        zoom:8,
        center:{lat:37.128285,lng:-8.539157}
      }
      
      // New map
      var map = new google.maps.Map(document.getElementById('map'), options);

      // Listen for click on map
      google.maps.event.addListener(map, 'click', function(event){
        // Add marker
        addMarker({coords:event.latLng});
      });

      /*
      // Add marker
      var marker = new google.maps.Marker({
        position:{lat:42.4668,lng:-70.9495},
        map:map,
        icon:'C:\Users\MDLABS\Desktop\nice taxy drivers traker\Taxi-icon.png'
      });

      var infoWindow = new google.maps.InfoWindow({
        content:'<h1>Lynn MA</h1>'
      });

      marker.addListener('click', function(){
        infoWindow.open(map, marker);
      });
      */

      // Array of markers
      var markers = [
        {
          coords:{lat:${lati},lng:${longi}},
          iconImage:'https://www.nicetaxi.eu/Taxi-icon.png',
          content:'<h1>driver 1</h1>'
        },
        {
          coords:{lat:37.128285,lng:-8.539157},
          content:'<h1>driver 2</h1>'
        },
        {
          coords:{lat:37.128285,lng:-8.539159}
        }
      ];

      // Loop through markers
      for(var i = 0;i < markers.length;i++){
        // Add marker
        addMarker(markers[i]);
      }

      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position:props.coords,
          map:map,
          //icon:props.iconImage
        });

        // Check for customicon
        if(props.iconImage){
          // Set icon image
          marker.setIcon(props.iconImage);
        }

        // Check content
        if(props.content){
          var infoWindow = new google.maps.InfoWindow({
            content:props.content
          });

          marker.addListener('click', function(){
            infoWindow.open(map, marker);
          });
        }
      }
    }
    function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBg8mazOCFsHlsOfTClG9Cugb1ddBPfldU&callback=initMap">
    </script>
    </body>
    </html>
8
  • 2
    "...but it seems not work." -> "Describe the problem. "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it" Commented Sep 3, 2021 at 13:12
  • 1
    What does the question title have to do with what's posted in the question itself? Commented Sep 3, 2021 at 13:14
  • You are setting the cookies with capitalized names (Lat, Lon) but are accessing with lowercase names (lat, lon). Also the way you are extracting the values doesn't seem right. Commented Sep 3, 2021 at 13:17
  • 1
    @Andreas: document.cookie is special. developer.mozilla.org/en-US/docs/web/api/document/… Commented Sep 3, 2021 at 13:17
  • @Pointy in the second code in the line coords:{lat:${lati},lng:${longi}} that is the question title about but this code is not correct Commented Sep 3, 2021 at 13:19

1 Answer 1

1

I have found the solution to make it work. This is the final working code that solves it:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>My Google Map</title>
        <style>
            #map {
                height: 400px;
                width: 100%;
            }
        </style>
    </head>
    <body>
    <h1>My Google Map</h1>
    <div id="map"></div>
    <script>
        var lati = parseFloat(getCookie("Lat"));
        var longi = parseFloat(getCookie("Long"));
    
        function initMap() {
            // Map options
            var options =
                {
                    zoom: 8,
                    center: {lat: lati, lng: longi}
                }
    
            // New map
            var map = new google.maps.Map(document.getElementById('map'), options);
    
            // Listen for click on map
            google.maps.event.addListener(map, 'click', function (event) {
                // Add marker
                addMarker({coords: event.latLng});
            });
    
            /*
            // Add marker
            var marker = new google.maps.Marker({
              position:{lat:42.4668,lng:-70.9495},
              map:map,
              icon:'C:\Users\MDLABS\Desktop\nice taxy drivers traker\Taxi-icon.png'
            });
    
            var infoWindow = new google.maps.InfoWindow({
              content:'<h1>Lynn MA</h1>'
            });
    
            marker.addListener('click', function(){
              infoWindow.open(map, marker);
            });
            */
    
            // Array of markers
            var markers = [
                {
                    coords: {lat: 37.128285, lng: -8.539157},
                    iconImage: 'https://www.nicetaxi.eu/Taxi-icon.png',
                    content: '<h1>driver 1</h1>'
                }
            ];
    
            // Loop through markers
            for (var i = 0; i < markers.length; i++) {
                // Add marker
                addMarker(markers[i]);
            }
    
            // Add Marker Function
            function addMarker(props) {
                var marker = new google.maps.Marker({
                    position: props.coords,
                    map: map,
                    //icon:props.iconImage
                });
    
                // Check for customicon
                if (props.iconImage) {
                    // Set icon image
                    marker.setIcon(props.iconImage);
                }
    
                // Check content
                if (props.content) {
                    var infoWindow = new google.maps.InfoWindow({
                        content: props.content
                    });
    
                    marker.addListener('click', function () {
                        infoWindow.open(map, marker);
                    });
                }
            }
        }
    
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }
    </script>
    <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&callback=initMap">
    </script>
    </body>
    </html>
Sign up to request clarification or add additional context in comments.

Comments

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.