【问题标题】:Google Maps JavaScript API v3 drawing line between two location [duplicate]Google Maps JavaScript API v3在两个位置之间画线[重复]
【发布时间】:2014-04-02 10:54:29
【问题描述】:

请帮帮我,我真的坚持这个! 我的代码是:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

  var address2 = document.getElementById('address2').value;
  geocoder.geocode( { 'address2': address2}, function(results2, status2) {
    if (status2 == google.maps.GeocoderStatus.OK) {

      var marker2 = new google.maps.Marker({
          map: map,
          position: results2[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

  var myTrip = [address,address2];
    var flightPath = new google.maps.Polyline({
      path:myTrip,
      strokeColor:"#00F",
      strokeOpacity:0.8,
      strokeWeight:2
  });

flightPath.setMap(map);
}


google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="address 1">
      <input id="address2" type="textbox" value="address 2">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

我想在输入中输入两个地址,将其分别转换为纬度/经度,在地图上放置两个标记并在它们之间画一条直线! 我的代码不起作用,它只显示第一个地址,仅此而已...... 提前谢谢你!

【问题讨论】:

  • 签入console你遇到了什么错误?

标签: javascript google-maps-api-3


【解决方案1】:

好吧,您似乎至少有语法错误 (address2),因为您定义了:

geocoder.geocode( { 'address2': address2}, function(results2, status2) {

代替:

geocoder.geocode( { 'address': address2}, function(results2, status2) {

但是,您在定义实际折线时也遇到了错误,因为地理编码是异步,您不能在地理编码线之后调用折线的创建,而是需要创建单独的方法或类似的回调功能,即地理编码完成时调用。否则,您只是在处理 undefined 值。

因此,我决定添加名为 displayMarkers() 的方法,该方法从每个地理编码请求中调用,进而检查所有地址是否都经过地理编码并采取相应措施。以下是修改后的代码:(也可以不刷新页面,你可以尝试连续搜索多个地址)。

var geocoder;
var map;
var geocodeMarkers = [];
var flightPath;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {

  // Emptying last addresses because of recent query
  for(var i = 0; i < geocodeMarkers.length; i++) {
     geocodeMarkers[i].setMap(null);
  }  

  // Empty array
  geocodeMarkers.length = 0;

  // Empty flight route
  if(typeof flightPath !== "undefined") {
     flightPath.setMap(null);
     flightPath = undefined;
  }  

  var address = document.getElementById('address').value;

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        // Adding marker to geocodeMarkers
        geocodeMarkers.push(
            new google.maps.Marker({
              position: results[0].geometry.location
            })
        );

        // Attempting to display
        displayMarkers();

        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }

  });

  var address2 = document.getElementById('address2').value;

  geocoder.geocode( { 'address': address2 }, function(results2, status2) {

    if (status2 == google.maps.GeocoderStatus.OK) {

       // Adding marker to geocodeMarkers
       geocodeMarkers.push(
           new google.maps.Marker({
               position: results2[0].geometry.location
           })
       );

       // Attempting to display
       displayMarkers();

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }

 });


}

function displayMarkers() {

  // If geocoded successfully for both addresses
  if(geocodeMarkers.length === 2) {

    // Bounds for the markers so map can be placed properly
    var bounds = new google.maps.LatLngBounds(
       geocodeMarkers[0].getPosition(),
       geocodeMarkers[1].getPosition()
    );

    // Fit map to bounds
    map.fitBounds(bounds);

    // Setting markers to map
    geocodeMarkers[0].setMap(map);
    geocodeMarkers[1].setMap(map);    

    flightPath = new google.maps.Polyline({
       path: [geocodeMarkers[0].getPosition(), geocodeMarkers[1].getPosition()],
       strokeColor:"#00F",
       strokeOpacity:0.8,
       strokeWeight:2,
       map: map
    });

  }

}

google.maps.event.addDomListener(window, 'load', initialize);

工作 jsfiddle 示例:js fiddle demonstration 1

编辑:

在进一步的 cmets 之后,本主题的作者希望将地图置于第一个地理编码标记的中心。它是通过更改以下几行来完成的:

// Bounds for the markers so map can be placed properly
var bounds = new google.maps.LatLngBounds(
   geocodeMarkers[0].getPosition(),
   geocodeMarkers[1].getPosition()
);

// Fit map to bounds
map.fitBounds(bounds);

收件人:

// Center map to first geocoded location
map.setCenter(geocodeMarkers[0].getPosition());

为此工作的jsfiddle:js fiddle demonstration 2

【讨论】:

  • 非常感谢毛诺!我真的很感激你的帮助!它工作得很好!另外,如果您能再帮助我一点,那就太好了!在对位置进行地理编码后,我尝试将地图居中到第一个地址,但没有成功:(这是我尝试的鳕鱼:if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[ 0].geometry.location); ...提前非常感谢您!
  • @user3488958 好吧,我在这里创建了关于它的示例:jsfiddle.net/4rsME/2 您可以在脚本底部的 displayMarkers 方法中看到地图居中。我没有把它作为这个答案的一部分,但如果现在已经完成,请随时接受。干杯。 :)
  • 非常感谢您的帮助!我真的很感激!
  • 毛诺,还有一件事。我很惭愧,但请输入代码,以显示这两个位置之间的距离(公里)。在“面板”DIV。提前感谢您,对此深表歉意!
  • 超出了这个问题,但我想将它包含在 cmets 中并没有什么害处:jsfiddle.net/4rsME/3(请参阅我添加了 &libraries=geometry)到 js map api url.. 所以它应该更改为:maps.googleapis.com/maps/api/… - 其余的,如果出现问题,请提出新问题或使用搜索 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
相关资源
最近更新 更多