MikiMrki
MikiMrki

Reputation: 195

Locate user position with google maps v3

Here I have a code for show a places for users, but I want to show places based on user location.

How I can get user's location and show on map?

I have:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>

function initialize() {

  var markers = [];
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(-33.8902, 151.1759),
      new google.maps.LatLng(-33.8474, 151.2631));
  map.fitBounds(defaultBounds); ... ... ... etc.

I try to add on sensor:true, but it didn't work.

Is there any way to solve this?

Upvotes: 1

Views: 1460

Answers (2)

PMG
PMG

Reputation: 190

Include this to locate the map center at current coordinates:

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

      var infowindow = new google.maps.InfoWindow({
        map: map,
        position: pos,
        content: 'Here you are.'
      });

      map.setCenter(pos);
    });
  }

Upvotes: 1

Mike Jeffrey
Mike Jeffrey

Reputation: 3209

You can try to geolocate your user with the browser's built-in geolocation service (which uses the W3C Geolocation standard, so should be supported by all browsers that support HTML5).

There's code you can copy and paste in the Google Maps JavaScript API v3 documentation, here: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

(The sensor parameter, by the way, just tells Google that you're using a sensor to determine position; it doesn't act as a sensor itself).

Upvotes: 3

Related Questions