简体   繁体   中英

Geo location Google Places API javascript

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);
  });
}

我已经设法使代码正常工作 - 我添加了一个 showError 函数并在用户点击拒绝时调用它,它设置默认坐标然后初始化地图。

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