简体   繁体   English

地理位置 Google Places API javascript

[英]Geo location Google Places API javascript

the below code shows bars near my location using the Google Places API.下面的代码使用 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.我想要的是地图在 else 语句中默认为伦敦坐标。

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 函数并在用户点击拒绝时调用它,它设置默认坐标然后初始化地图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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