-2

the below code shows bars near my location using the Google Places API. However, if the user clicks don't allow on the browser warning 'use your location' the map doesn't load. What I would like is for the map to default to the London co-ordinates in the else statement.

var temp_lat = '';
var temp_lng = '';
var map;
var infowindow;
getLocation();

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    temp_lat = 51.507222; //set default lat value
    temp_lng = -0.1275; //set default lng value
  }
}

function showPosition(position) {
  temp_lat = position.coords.latitude;
  temp_lng = position.coords.longitude;
  initMap();
}


function initMap() {
  var location = {
    lat: temp_lat,
    lng: temp_lng
  };
  map = new google.maps.Map(document.getElementById('map'), {
    center: location,
    zoom: 15
  });
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
      location: location,
      radius: 50000,
      keyword: ['bar']
    },
    callback);
}

function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}
theJ
  • 395
  • 5
  • 25
  • Code is now updated on the fiddle to reflect the one on the post. I know what the issue, however, my javascript is rusty so struggling to fix. Basically the showPostion function will set the co-ords then initialize the map. If geolocation is dismissed i.e false the latitude and longitude will never be set and it will fail before the map can be intilized. I need some some sort of boolean in the showPostion function, but not sure where to start. – theJ Feb 21 '18 at 19:10
  • The geolocation `getCurrentPosition` is an asynchronous function. This means it can take some time to return a position. Why don't you do it the other way around? First, create your map and set it to your default location (London), and then, if geolocation works, update your map to the user position with `map.setCenter()`. – MrUpsidown Feb 21 '18 at 19:25

1 Answers1

1

I have managed to get the code working - I added a showError function and called it if a user hits deny, it sets the default co-ords then initializes the map.

theJ
  • 395
  • 5
  • 25