为什么我不能将Google Maps getCurrentPosition与地点搜索API结合使用 [英] Why can't I combine Google maps getCurrentPosition with place search API

查看:48
本文介绍了为什么我不能将Google Maps getCurrentPosition与地点搜索API结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个站点,使用户可以按下按钮或链接,并向他们显示附近位置的商店.我使用了 getCurrentPosition 并放置了搜索服务,它们可以单独很好地工作,但是当我将两者结合使用时,什么也没有发生.我认为有一种不知道如何合并它们的方法.

I am trying to build a site that will enable the users to press a button or a link and it will show them stores near their location. I have used getCurrentPosition and place search services, which work well separately, but nothing happens when I combine the two. I think there is a way of combining them that I don't know how.

下面是我合并的代码.

<head>
    <title>Churchtraker final</title>
    <meta name="viewport" content = "initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        #map {
            height:100%;        
        }   
    </style>
    <script>
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(initMap);
        } else {
            error('Sorry , Geolocation is not supported in your device');
        }
        var map;
        var infowindow;

        function initMap() {
            var latitude = new google.maps.LatLng(position.coords.latitude);
            var longitude = new google.maps.LatLng(position.coords.longitude);
            var coords = { lat: latitude, lng: longitude };
            map = new google.maps.Map(document.getElementById('map'), {
                      center: coords,
                      zoom:15
                  });
            infowindow = new google.maps.InfoWindow();
            var service = new google.maps.places.PlacesService(map);
            service.nearbySearch({
                location: coords,
                radius:7000,
                type: ['store']
            }, 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() {
            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>
</head>
<body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=My_API_KEY&libraries=places&callback=initMap" async defer></script>
</body>

推荐答案

地理位置服务是异步的,您需要在可用的时间/位置在回调函数中使用结果.您还需要将参数放在回调函数中(在您的情况下,应为initMap(position),但是...您也不能将其用作API异步加载的回调.一种选择是从initMap函数调用地理位置代码,如果成功,则更新地图.

The geolocation service is asynchonous, you need to use the results in the callback function, when/where it is available. You also need to put the argument in the callback function (in your case, should be initMap(position), but... you can't use that as the callback for the asynchronous load of the API as well. One option is to call the geolocation code from the initMap function, and update the map if it succeeds.

function initMap() {
  map = new google.maps.Map(
    document.getElementById("map"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  navigator.geolocation.getCurrentPosition(function(position) {
    var coords = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };

    map.setOptions({
      center: coords,
      zoom: 15
    });

    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
      location: coords,
      radius: 7000,
      type: ['store']
    }, callback);
  }, errorHandler, geoLocOptions);
}

概念提琴证明

代码段:

var map;
var currentLocation;
var geoLocOptions = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function initMap() {
  map = new google.maps.Map(
    document.getElementById("map"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  navigator.geolocation.getCurrentPosition(function(position) {
    var coords = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };

    map.setOptions({
      center: coords,
      zoom: 15
    });

    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
      location: coords,
      radius: 7000,
      type: ['store']
    }, callback);
  }, errorHandler, geoLocOptions);
}
google.maps.event.addDomListener(window, "load", initMap);

function errorHandler(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

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

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

这篇关于为什么我不能将Google Maps getCurrentPosition与地点搜索API结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆