谷歌地图 - 在地理位置传递lat / lng变量之前加载地图

时间:2017-01-28 00:36:17

标签: javascript google-maps variables geolocation

我添加了一个地理定位功能来显示用户的当前位置,但我认为在脚本获取位置变量之前正在加载地图功能。

我是JavaScript的新手,我想知道是否可以在下一个函数加载之前等待?

我已经查看了超时功能,但这似乎不起作用。

任何帮助都会很棒

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
  <link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    
  

  <style type="text/css">
    #mapCanvas {
    width: 300px;
    height: 300px;
    float: left;
  }
  #infoPanel {
    float: left;
    margin-left: 10px;
  }
  #infoPanel div {
    margin-bottom: 5px;
  }
  </style>

  <title>Google Maps Drag Marker</title>


<script type='text/javascript'>//<![CDATA[
var lat = 51.49575692748839;
var lng = -0.14600197187496633;

// sets your location as default
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
 
    lat = position.coords["latitude"];
    lng = position.coords["longitude"];

   console.log(lat, lng);

  },
  function(error) {
    console.log("Error: ", error);
  },
  {
    enableHighAccuracy: true
  }
  );
}

	//
	
$(window).load(function(){
var geocoder;
var map;
var marker;

	codeAddress = function (getLocation) {
    geocoder = new google.maps.Geocoder();  
	
   var address = lat + ", " + lng;
  console.log(lat, lng);
  
  geocoder.geocode( { 'address': address}, function(results, status,getLocation) {
    if (status == google.maps.GeocoderStatus.OK) {
      map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 16,
            streetViewControl: false,
          mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
              mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP] 
    },
    center: results[0].geometry.location,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
      map.setCenter(results[0].geometry.location);
      marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          draggable: true,
          title: 'My Title'
      });
      updateMarkerPosition(results[0].geometry.location);
      geocodePosition(results[0].geometry.location);
        
      // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });
      
  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });
  
  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
      map.panTo(marker.getPosition()); 
  });
  
  google.maps.event.addListener(map, 'click', function(e) {
    updateMarkerPosition(e.latLng);
    geocodePosition(marker.getPosition());
    marker.setPosition(e.latLng);
  map.panTo(marker.getPosition()); 
  }); 
  
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('info').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
  document.getElementById("info1").value = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function updateMarkerAddress(str) {
  document.getElementById('address').innerHTML = str;
  document.getElementById("address1").value = str;
}
});//]]> 

</script>

  
</head>

<body onload="codeAddress();">

  <div id="panel">
      
  </div>  
  <div id="mapCanvas"></div>
  <div id="infoPanel">
    <b>Marker status:</b>
    <div id="markerStatus"><i>Click and drag the marker.</i></div>
    <b>Current position:</b>
    <div id="info"></div>
    <input type="text" id="info1" value="">
    <b>Closest matching address:</b>
    <div id="address"></div>
    <input type="text" id="address1" value="">
  </div>
</body>



</html>

1 个答案:

答案 0 :(得分:0)

这个具体问题的解决方案是:

更改此部分

var lat = 51.49575692748839;
var lng = -0.14600197187496633;

// sets your location as default
if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(function(position) {

      lat = position.coords["latitude"];
      lng = position.coords["longitude"];

      console.log(lat, lng);

   },
   function(error) {
      console.log("Error: ", error);
   },
   {
      enableHighAccuracy: true
   });
}

var lat = 51.49575692748839;
var lng = -0.14600197187496633;

// sets your location as default
if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(function(position) {

      lat = position.coords["latitude"];
      lng = position.coords["longitude"];

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

      updateMarkerPosition(ll);
      geocodePosition(ll);
      marker.setPosition(ll);
      map.panTo(ll);

      console.log(lat, lng);

   },
   function(error) {
      console.log("Error: ", error);
   },
   {
      enableHighAccuracy: true
   });
}

并将其包含在

$(window).load(function(){  ....    });

这应该使地图加载初始标记位置,并且只要用户位置可用,地图就会发生变化。

Geolocation.getCurrentPosition()的第一个参数是在成功检测到用户位置时调用的函数。