0

我正在尝试在 Google Maps 上使用 Geolocation,但是当页面加载时,什么也没发生

<script>
var initialLocation;
var map;
var markersArray = [];
function initialize() {
  var mapOptions = {
  zoom: 15,
  center: new google.maps.LatLng(-34.397, 150.644),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  disableDefaultUI: false,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.LARGE
  }
};

  map = new google.maps.Map(document.getElementById('gmaps'),
  mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    deleteOverlays();
    addMarker(event.latLng);
    updateTextFields(latitude, longitude);
  });

  google.maps.event.addListener(marker, 'click', function(event) {
    showInfo(window);
  });

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success);
    alert('Browser Supports but Im not doing anything yet');
  } else {
    error('Geo Location is not supported');
  }
}

function updateTextFields(lati, longi) {
  $('#inputLatitude').val(lati);
  $('#inputLongitude').val(longi);
}


function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

function loadScript() {
  var script = document.createElement('script');
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' +
  'callback=initialize';
  document.body.appendChild(script);
}

$(document).ready(function() {
$(window).resize(function () {
    var h = $(window).height(),
        offsetTop = 190; // Calculate the top offset

    $('#gmaps').css('height', (h - offsetTop));
  }).resize();
  window.onload = loadScript;
});


</script>

在此处输入图像描述

4

1 回答 1

0

您正在为窗口加载window.onload 后分配一个功能;因此它不会被调用。

以下会更好:

$(document).ready(function() {
  $(window).resize(function () {
    var h = $(window).height(),
        offsetTop = 190; // Calculate the top offset

    $('#gmaps').css('height', (h - offsetTop));
  }).resize();
  loadScript();
});

此外:

navigator.geolocation.getCurrentPosition(success);

需要一个success将地理位置作为输入参数的函数。我在您的代码中没有看到这样的功能。

于 2013-03-04T18:17:22.997 回答