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

问题描述 投票:-1回答:1

我做了一个功能,在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()功能来显示用户位置标记,但它覆盖了酒店图标。因此,当我首先刷新页面微秒用户位置显示,而酒店图标将覆盖它。这是我的图像与o / p上面的代码。

Output of Fiddle Snippet

javascript google-maps google-maps-api-3 google-maps-markers
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.