Link to home
Start Free TrialLog in
Avatar of error2013
error2013

asked on

Javascript a current location marker to map to plot in current map

I have some code that uses javascript and plots multiple markers in a map.

Here is the code:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

Open in new window


This work first but I want to add a timer that plots another marker with my current location that replaces the center location here:

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(-33.92, 151.25),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Open in new window


How can I do this or plot a pointer in of me current location in this map?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

what miss here : https://developers.google.com/maps/documentation/javascript/geolocation

this part :

// Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }

Open in new window

Avatar of error2013
error2013

ASKER

Yes I saw that but I don't know how to integrate is into the code I provided. Could you please help?
try to copy/paste and let me know
I tried this:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">

  //NEW

  if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }

      }
      

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }

      // END NEW


    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

Open in new window


But get this error:

Uncaught SyntaxError: Unexpected token }

Points to line 30:  

handleLocationError(false, infoWindow, map.getCenter());

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, the error seems to have gone but what I cannot see is the marker with my current location although I can see the other markers.
please confirm you get three alert box with the following code :

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Google Maps Multiple Markers</title>
    <script src="http://maps.google.com/maps/api/js?sensor=false"
            type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>

<script type="text/javascript">

    //NEW
    
    function getMyCurrentLocationAndSetItAsCenter() {
alert("one");
        if (navigator.geolocation) {
alert("three");
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                infoWindow.setPosition(pos);
                infoWindow.setContent('Location found.');
                infoWindow.open(map);
                map.setCenter(pos);
            }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
alert("two");
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
        }
    }
    
    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
            'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
    }

    // END NEW


    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.92, 151.25),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

    setTimeout(getMyCurrentLocationAndSetItAsCenter, 3000);

</script>
</body>
</html>

Open in new window

No, I only get Alert 1 and 3 ... I'm not getting 2
you should get the three with the following with your coords in the last one :
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Google Maps Multiple Markers</title>
    <script src="http://maps.google.com/maps/api/js?sensor=false"
            type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>

<script type="text/javascript">

    //NEW
    
    function getMyCurrentLocationAndSetItAsCenter() {
alert("one");
        if (navigator.geolocation) {
alert("two");
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                infoWindow.setPosition(pos);
                infoWindow.setContent('Location found.');
                infoWindow.open(map);
                map.setCenter(pos);
alert("three\n"+JSON.stringify(pos));
            }, function() {
                handleLocationError(true, infoWindow, map.getCenter());
            });
        } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
        }
    }
    
    function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
            'Error: The Geolocation service failed.' :
            'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
    }

    // END NEW


    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.92, 151.25),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

    setTimeout(getMyCurrentLocationAndSetItAsCenter, 3000);

</script>
</body>
</html>

Open in new window

I still don't get the 3rd alert.
I've tried to test it by running it locally and on my host (which is not https)...
Could that be the problem?
How are you testing it?
I've tried it on my mobile and I even got the co-dinates to come out but nothing plots on the map, only the locations have pointers not my location
replace the third alert
by :
new google.maps.Marker({
            position: new google.maps.LatLng(pos.lat, pos.lng),
            map: map
        });

Open in new window

Not working either.

Ok lets reverse it?

I managed to get the geolocation marker to appear with the following code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title>Blank App</title>
        <script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>
    </head>
    <body>
    <div id="map" style="width: 500px; height: 400px;"></div>

    <div id="geolocation"></div>

<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">

	document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("navigator.geolocation works well");
        getMapLocation();
    }

    var Latitude = undefined;
	var Longitude = undefined;
 
	// Get geo coordinates
	 
	function getMapLocation() {
	 
	    navigator.geolocation.getCurrentPosition
	    (onMapSuccess, onMapError, { enableHighAccuracy: true });
	}
 
	// Success callback for get geo coordinates
	 
	var onMapSuccess = function (position) {
	 
	    Latitude = position.coords.latitude;
	    Longitude = position.coords.longitude;
	 
	    getMap(Latitude, Longitude);
	 
	}
 
	// Get map by using coordinates
	 
	function getMap(latitude, longitude) {
	 
	    var mapOptions = {
	        center: new google.maps.LatLng(0, 0),
	        zoom: 1,
	        mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	 
	    map = new google.maps.Map
	    (document.getElementById("map"), mapOptions);
	 
	 
	    var latLong = new google.maps.LatLng(latitude, longitude);
	 
	    var marker = new google.maps.Marker({
	        position: latLong,
	        icon: {
		      url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
		    }
	    });
	 
	    marker.setMap(map);
	    map.setZoom(15);
	    map.setCenter(marker.getPosition());
	}
 
	// Success callback for watching your changing position
	 
	var onMapWatchSuccess = function (position) {
	 
	    var updatedLatitude = position.coords.latitude;
	    var updatedLongitude = position.coords.longitude;
	 
	    if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
	 
	        Latitude = updatedLatitude;
	        Longitude = updatedLongitude;
	 
	        getMap(updatedLatitude, updatedLongitude);
	    }
	}
 
	// Error callback
	 
	function onMapError(error) {
	    console.log('code: ' + error.code + '\n' +
	        'message: ' + error.message + '\n');
	}
	 
	// Watch your changing position
	 
	function watchMapPosition() {
	 
	    return navigator.geolocation.watchPosition
	    (onMapWatchSuccess, onMapError, { enableHighAccuracy: true });
	}


</script>
        
    </body>
</html>

Open in new window


How do I add the marker list to this code?
just copy/paste after