简体   繁体   中英

How to use google maps api to display map and marker at users location

I am using the google maps and geolocation api to try display a map thats centered on their location with a marker there, however the map isn't displaying. I initially got it to display but then once I added the getCurrentPosition function it no longer displays. What am I missing and how do I fix it?

  var map,latitude,longitude;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(updateCoords);
  }
  else {
    alert("geolocation not supported by this browser");
  }

  function updateCoords(position){
    latitude: position.coords.latitude,
    longitude:  position.coords.longitude
  }

  function initMap() {
    var options = {
      center = {
        lat:  latitude,
        lng:  longitude
      },
      zoom: 15
    }
    map = new google.maps.Map(document.getElementById('map'),options);

    var marker = new google.maps.Marker({
        position: map.getCenter(),
        title: "Your Location",
        map: map
      });
      marker.setMap(map);

  };

I have changed my answer so that the marker will display. Because getCurrentPosition is asyncronous your original latitude and longitude values were only set after the map tried to initiate.

This code only adds the marker to the map after the location is found.

 var map,latitude,longitude; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(updateCoords); } else { alert("geolocation not supported by this browser"); } function updateCoords(position){ var center = { lat: position.coords.latitude, lng: position.coords.longitude } var marker = new google.maps.Marker({ position: center, title: "Your Location", map: map }); marker.setMap(map); map.setCenter(center); } function initMap() { // all fields inside a json object use : instead of = var options = { center: { lat: 0, lng: 0 }, zoom: 15 } map = new google.maps.Map(document.getElementById('map'),options); }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM