在回调函数中设置标记,在创建地图后用户的位置可用

时间:2017-12-22 10:34:00

标签: javascript google-maps google-maps-api-3 google-maps-markers

我制作了一个在google map中显示最近的酒店的功能。我的代码如下。

var map;

  function initMap() {

    var latlng = new google.maps.LatLng(28.535516,77.391026);

    if (navigator.geolocation) {
      try {
        navigator.geolocation.getCurrentPosition(function(position) {
          var myLocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
          };
          setPos(myLocation);
        });
      } catch (err) {
        var myLocation = {
          lat: 25.2048,
          lng: 55.2708
        };
        setPos(myLocation);
      }
    } else {
      var myLocation = {
        lat: 25.2048,
        lng: 55.2708
      };
      setPos(myLocation);
    }
  }

  function setPos(myLocation) {
    map = new google.maps.Map(document.getElementById('map'), {
      center: myLocation,
      zoom: 10
    });
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
      location: myLocation,
      radius: 4000,
      types: ['hotels']
    }, processResults);
  }

  function processResults(results, status, pagination) {
    if (status !== google.maps.places.PlacesServiceStatus.OK) {
      return;
    } else {
      createMarkers(results);
    }
  }

  function createMarkers(places) {
    var bounds = new google.maps.LatLngBounds();
    var placesList = document.getElementById('places');
    for (var i = 0, place; place = places[i]; i++) 
    {
      var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };
      var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        animation: google.maps.Animation.DROP,
        position: place.geometry.location
      });

      bounds.extend(place.geometry.location);
    }
    map.fitBounds(bounds);
  }
html,body {
      margin: 0;
      padding: 0;
    }

    #map {
      height: 500px;
      margin: 10px auto;
      width: 800px;
    }
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places&callback=initMap" async defer></script>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuBzeYkYimIquGG5KkIcB6vFmtHMUzDFo&libraries=places"></script>

<div id="map"></div>

以上示例返回我最近的酒店用户所在地。但我想也显示用户位置指针。 那么我如何在这里显示用户位置。

我还尝试自定义添加initMap()功能以显示用户位置标记,但 OVERRIDE 使用Hotels图标。因此,当我首先刷新页面微秒用户位置显示,而酒店图标将覆盖它。 这是我的图像,上面有代码的o / p。

Output of Fiddle Snippet

1 个答案:

答案 0 :(得分:1)

将标记的创建添加到setPos函数中(地理定位结果可用且已创建地图。

proof of concept fiddle

地理位置失败时: screenshot of resulting map on http (when geolocation fails)

当地理位置有效时,它会显示我当前的位置。

代码段

var map;

function error() {
  console.log("error!")
  var myLocation = {
    lat: 25.2048,
    lng: 55.2708
  };
  setPos(myLocation);
}

function initMap() {

  var latlng = new google.maps.LatLng(28.535516, 77.391026);

  if (navigator.geolocation) {
    try {
      navigator.geolocation.getCurrentPosition(function(position) {

        var myLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        setPos(myLocation);
      }, error);
    } catch (err) {
      var myLocation = {
        lat: 25.2048,
        lng: 55.2708
      };
      setPos(myLocation);
    }
  } else {
    var myLocation = {
      lat: 25.2048,
      lng: 55.2708
    };
    setPos(myLocation);
  }
}

function setPos(myLocation) {
  map = new google.maps.Map(document.getElementById('map'), {
    center: myLocation,
    zoom: 10
  });
  var marker = new google.maps.Marker({
    position: myLocation,
    map: map,
    title: "My Position"
  })
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: myLocation,
    radius: 4000,
    types: ['hotels']
  }, processResults);
}

function processResults(results, status, pagination) {
  if (status !== google.maps.places.PlacesServiceStatus.OK) {
    return;
  } else {
    createMarkers(results);
  }
}

function createMarkers(places) {
  var bounds = new google.maps.LatLngBounds();
  var placesList = document.getElementById('places');
  for (var i = 0, place; place = places[i]; i++) {
    var image = {
      url: place.icon,
      size: new google.maps.Size(71, 71),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(25, 25)
    };
    var marker = new google.maps.Marker({
      map: map,
      icon: image,
      title: place.name,
      animation: google.maps.Animation.DROP,
      position: place.geometry.location
    });

    bounds.extend(place.geometry.location);
  }
  map.fitBounds(bounds);
}
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

#map {
  height: 100%;
  margin: 10px auto;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
<div id="map"></div>