如何在地图上显示用户位置以及我的标记?

时间:2016-04-01 15:28:31

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

此代码允许我查看我在地图上制作的标记,是否有人知道如何在地图上简单地显示用户的位置?这是我到目前为止的代码...... 每当我尝试按照谷歌地图API开发人员的说明,我似乎无法在地图上显示用户位置以及我已经工作的标记,请有人帮忙!非常感谢,谢谢。雅各布

<script type="text/javascript">
var customIcons = {
  point: {
    icon: 'img/points.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  },
};
function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(53.8, -1.55),
    zoom: 14,
    mapTypeId: 'roadmap'
  });
  var infoWindow = new google.maps.InfoWindow;
  // Change this depending on the name of your PHP file
  downloadUrl("phpsqlajax_genxml.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var type = markers[i].getAttribute("type");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "<b>" + name + "</b> <br/>" + type;
      var icon = customIcons[type] || {};
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icon.icon,
        shadow: icon.shadow
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });
}
function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}
function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };
  request.open('GET', url, true);
  request.send(null);

}

function doNothing() {}
//]]>

2 个答案:

答案 0 :(得分:0)

您可以使用这样的初始化函数或提取您需要的部分

function initialize() {

   if(google.loader.ClientLocation) {
      loc.lat = google.loader.ClientLocation.latitude;
      loc.lng = google.loader.ClientLocation.longitude;

      var latlng = new google.maps.LatLng(loc.lat, loc.lng);

      var myOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
     };
     var map = new google.maps.Map(document.getElementById("map"), myOptions);
     var marker = new google.maps.Marker({
      position: latlng,
      map: map
      });

  }
}

答案 1 :(得分:0)

使用geolocation-marker库。这使得这很简单。

免责声明:我是图书馆的作者。