-1

I have implemented a tutorial on how to make users select locations on the map and store it in the database, from google maps API.

However, there seems to be a problem that i cant fix, the map doesn't get the user's current location, it only provides a given coordinate which is to be defined in the code. For example the tutorial defines the map coordinates in California :

var map;
      var marker;
      var infowindow;
      var messagewindow;

      function initMap() {
        var california = {lat: 37.4419, lng: -122.1419};
        map = new google.maps.Map(document.getElementById('map'), {
          center: california,
          zoom: 13
        });

        infowindow = new google.maps.InfoWindow({
          content: document.getElementById('form')
        });

        messagewindow = new google.maps.InfoWindow({
          content: document.getElementById('message')
        });

        google.maps.event.addListener(map, 'click', function(event) {
          marker = new google.maps.Marker({
            position: event.latLng,
            map: map
          });


          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map, marker);
          });
        });
      }

      function saveData() {
        var name = escape(document.getElementById('name').value);
        var address = escape(document.getElementById('address').value);
        var type = document.getElementById('type').value;
        var latlng = marker.getPosition();
        var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address +
                  '&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();

        downloadUrl(url, function(data, responseCode) {

          if (responseCode == 200 && data.length <= 1) {
            infowindow.close();
            messagewindow.open(map, marker);
          }
        });
      }

      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request.responseText, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing () {
      }

The code above will show only the map of the coordinates defined in the code

the HTML for code is :

<div id="map" height="460px" width="100%"></div>
    <div id="form">
      <table>
      <tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>
      <tr><td>Address:</td> <td><input type='text' id='address'/> </td> </tr>
      <tr><td>Type:</td> <td><select id='type'> +
                 <option value='bar' SELECTED>bar</option>
                 <option value='restaurant'>restaurant</option>
                 </select> </td></tr>
                 <tr><td></td><td><input type='button' value='Save' onclick='saveData()'/></td></tr>
      </table>
    </div>
    <div id="message">Location saved</div>

I have tried to replace it with the following function which gets the current location but it didn't work out and the code stops showing me the map when i run the code :

 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (p) {
        var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        var mapOptions = {
            center: LatLng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        };


        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude
        });
        google.maps.event.addListener(marker, "click", function (e) {
            var infoWindow = new google.maps.InfoWindow();
            infoWindow.setContent(marker.title);
            infoWindow.open(map, marker);
        });
    });
} else {
    alert('Geo Location feature is not supported in this browser.');
}

HTML for this code will be : <div id="dvMap" style="width: 400px; height: 300px"></div>

and for sure the API source code :

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOURAPI">
    </script>

When I try each code separately each will give me a different output, so the first code will give me the same output of the google tutorial which has a map of a city . and the second code will give me a map that gets me the current location but if I tried to merge both it will not work.

could someone please tell me how can I get the map to function the same way in google maps tutorial plus the feature of making the map go straight to the user's location so he can store it easily instead of looking for it in a map of an entire city or country?

  • 1
    Is the 2nd bit of code still inside `initMap()`? If so, please update it to show the whole of that function. – Reinstate Monica Cellio Feb 16 '18 at 15:12
  • Possible duplicate of [Real time GPS Tracker on JUST HTML / JS and Google Maps to be run on a handphone? Is it possible?](https://stackoverflow.com/questions/3305225/real-time-gps-tracker-on-just-html-js-and-google-maps-to-be-run-on-a-handphone) – dolftax Feb 16 '18 at 15:13
  • 1
    Is geolocation enabled in your browser? What happens if you add `alert('Hello');` in your `getCurrentPosition()` function? – MrUpsidown Feb 16 '18 at 15:16
  • Mr/Ms Archer, I didn't understand what you mean by the 2nd bit of code, but i will update it with the whole code right now. Mr/Ms Jaipradeesh this is about tracking and storing I just want the current position to be stored like if he wants to store his address. Mr/Ms Upsidown yes it is enabled , I did what you said and it stopped showing the map :| – Hasnaa Waked Feb 16 '18 at 15:23
  • Show the minimal code needed to reproduce the error. In your `getCurrentPosition()` function you are only declaring the maps options object. You are not actually creating a map... So either you missed that, or some code is missing. – MrUpsidown Feb 16 '18 at 15:24
  • I observer that you have alert('Hello'); inside json object var mapOptions = { ...}, this is wrong, move alert('Hello'); outside. – toto Feb 16 '18 at 15:30
  • Mr.Upsidown I have updated it as you requested, you can see the full JS code now. Thank you – Hasnaa Waked Feb 16 '18 at 15:31
  • Ms toto , that was a trial requested from a comment above, i'll remove it now – Hasnaa Waked Feb 16 '18 at 15:32
  • 1
    Where is your HTML code?? You should post **all the necessary code** so that we are able to reproduce the problem! Check your map creation. In the first piece of code the map DIV is `map` and in the second it is `dvMap` so which one is correct?! – MrUpsidown Feb 16 '18 at 15:58

2 Answers2

0

Your code contains several issues that I will not correct here.

Add this at the end of your initMap() function and it will center the map on your location without changing any other functionality of your first script.

if (navigator.geolocation) {

  navigator.geolocation.getCurrentPosition(function(p) {
    var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);

    // Set the map center on user location
    map.setCenter(LatLng);
  });

} else {
  alert('Geo Location feature is not supported in this browser.');
}
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
-1

Try it:

   var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, options);
    } else {
        alert('Geo Location feature is not supported in this browser.');
    }

    function success(p) {
        var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        var mapOptions = {
            center: LatLng,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        };


        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude
        });
        google.maps.event.addListener(marker, "click", function (e) {
            var infoWindow = new google.maps.InfoWindow();
            infoWindow.setContent(marker.title);
            infoWindow.open(map, marker);
        });
    }

    function error(err) {
        alert('ERROR(' + err.code + '): ' + err.message);
    }
toto
  • 1,180
  • 2
  • 13
  • 30
  • Ms.Toto, that was a trial requested from a comment above, i removed it, and i have updated the code. please check it – Hasnaa Waked Feb 16 '18 at 15:35
  • when you execute: navigator.geolocation.getCurrentPosition the navigator show a windows permission when ask to user if enable the current position? – toto Feb 16 '18 at 16:18
  • Yes it shows me the window where it asks for allowing this page to get location and i click on Allow, So it show me the map with my current position. However, when i take this function into the first code within the question and i run the code the entire map stops showing and the browser doesn't ask for anything! – Hasnaa Waked Feb 16 '18 at 16:22
  • I updated the code, please try it and shared the result. – toto Feb 16 '18 at 16:26
  • one observation: the div map id is dvMap or should be divMap ? document.getElementById("dvMap") – toto Feb 16 '18 at 16:31
  • Thank you very much Ms/Mr Toto, it worked by Mr.Upsidown Answer, which is by modifying the first code instead of the second. Thanks again for your contribution i really appreciate it. :) – Hasnaa Waked Feb 16 '18 at 16:40