将Geo Location API与Google Places API集成

时间:2016-02-11 13:30:28

标签: javascript jquery html5 api web

所以我试图将两个工作脚本集成到一个。

我想查看当前位置10公里范围内的所有健身房。我可以通过静态位置使其值得,但是在地理位置集成方面存在问题。这就是我提出的建议,任何建议都会受到极大的赞赏。 感谢

>     

<div id="map"></div>
    <script>
var map;
var infowindow;
var pos;

function initMap() {    

    if (navigator.geolocation) {//GEO LOCATION, FINDS USERS LOCATION
    navigator.geolocation.getCurrentPosition(function(position) {
    pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }
     infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.');
      map.setCenter(pos);
    }
                                             )};


  var myLocation = pos; //Sets variable to geo location long and lat co-ordinates.

  map = new google.maps.Map(document.getElementById('map'), {
    center: myLocation, 
    zoom: 13
  });

  infowindow = new google.maps.InfoWindow({map: map});


  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: myLocation, //Uses geolocation to find the following
    radius: 10000,
    types: ['gym']
  }, 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);
  });
}

        };


    ////////////////////////////////
    </script>

2 个答案:

答案 0 :(得分:0)

此代码存在许多问题。这是一个小提琴,他们都解决和工作:

https://jsfiddle.net/jimedelstein/bfdhjsyy/

以下是代码:

<div id="map" style="width:500px; height:500px"></div>
<script>
var map;
var infowindow;
var pos;

function initMap() {

  if (navigator.geolocation) { //GEO LOCATION, FINDS USERS LOCATION
    navigator.geolocation.getCurrentPosition(function(position) {

      pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }
      map = new google.maps.Map(document.getElementById('map'), {
        center: myLocation,
        zoom: 13
      });
      infoWindow = new google.maps.InfoWindow({
        map: map
      });
      infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.');
      map.setCenter(pos);
      var myLocation = pos; //Sets variable to geo location long and lat co-ordinates.

      var service = new google.maps.places.PlacesService(map);
      service.nearbySearch({
        location: myLocation, //Uses geolocation to find the following
        radius: 10000,
        types: ['gym']
      }, 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);
  });
}

initMap();
</scrip>

你会注意到事情的顺序是主要问题。您必须等到地理定位回调以确保您有一个位置。在使用它们之前,您必须实例化地图和信息窗口。在infoWindow = new google.maps ...行中也有一个类型,W没有大写。

答案 1 :(得分:0)

你可以检查这种支持者是否允许地理位置

if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(setUsersLocation);
                showClosestGyms();
       }

在setuserslocation中,您可以设置标记用户位置

var userlocation;
  function setUsersLocation(position) {
        center = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        userlocation = new google.maps.Marker({
            position: center,
            map: map

        });
        map.setCenter(center);
        showClosestGyms();

    }

然后你可以通过按距离到用户位置排序健身房位置阵列来显示最近的健身房(假设你有#34; gymlocations&#34;这是所有健身房的阵列):

 function showClosestGyms(){

gymlocations.sort(function (x, y) {
    var xdistance = getDistanceBetweenMarkers(x.latitude, x.longtitude, clickmarker.getPosition().lat(), userlocation.getPosition().lng());
    var ydistance = getDistanceBetweenMarkers(y.latitude, y.longtitude, clickmarker.getPosition().lat(), userlocation.getPosition().lng());
    if (ydistance+""=="NaN" || xdistance < ydistance) {
        return -1;
    }
   else
        return 1;
});

健身房和用户位置之间的距离很简单:

   function getDistanceBetweenMarkers(lat1,long1, lat2,long2){

            var R = 6378137; // Earth’s mean radius in meter
            var dLat = rad(lat2 - lat1);
            var dLong = rad(long2 - long1);
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(rad(lat1)) * Math.cos(rad(lat2)) *
              Math.sin(dLong / 2) * Math.sin(dLong / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = R * c;
            return d; // returns the distance in meter

    }

不仅仅是排序后显示最近的体育馆位置:

for(var i=0;i<=10;i++){
var gymToShow = vm.gymlocations[i];
//...show gym...
//....
}

希望这会有所帮助。