Google Maps API,如何从机场代码获取lat?

时间:2015-05-08 16:12:30

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

我想知道如何从机场获取LATLONG。例如,我有机场代码"CPH" (Copenhagen),我需要从我的标记画一条线到那一点。 现在我的代码是:

        var flightPlanCoordinates = [
        new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()),
        new google.maps.LatLng(21.291982, -157.821856)
    ];
    flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 1
    });

    flightPath.setMap(map);

但我需要这条线去机场。我看过地理编码,但我不明白如何在机场使用它。有人可以为我做一个例子吗?谢谢! :)

1 个答案:

答案 0 :(得分:2)

使用地理编码器,它支持“CPH”缩写(您可能希望将其设为“CPH机场”)。

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

working fiddle

代码段:

var geocoder = new google.maps.Geocoder();
var map;
var CPH;
var bounds = new google.maps.LatLngBounds();

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

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

  google.maps.event.addListener(map, 'click', function(event) {
    var flightPlanCoordinates = [
      event.latLng,
      CPH
    ];
    bounds.extend(event.latLng);
    flightPath = new google.maps.Polyline({
      path: flightPlanCoordinates,
      geodesic: true,
      strokeColor: '#FF0000',
      strokeOpacity: 1.0,
      strokeWeight: 1
    });
    map.fitBounds(bounds);
    flightPath.setMap(map);
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>