页面加载时从邮政编码更新谷歌地图

Update google map from postcode on page load

本文关键字:邮政编码 更新 谷歌地图 加载      更新时间:2023-09-26

我正在尝试根据邮政编码值在页面加载时生成地图。

为了做到这一点,我正在对给定的动态邮政编码进行地理编码,我已经得到了它,可以从该动态邮政编码中给我一个经度和纬度。

邮政编码是从上一页的表格中发送的,并存储在url中,如下所示:

url.com?postcode=XXXXXX

现在的问题是如何将经度和纬度值连接起来,以传递到以下内容中:

center: new google.maps.LatLng(longitude, latitude)

这是我目前拥有的JS:

var postcodeValue = $('#map').attr('data-postcode');
  function latLong(location, callback) {
  var geocoder = new google.maps.Geocoder();
  var address = location;
  var longitude;
  var latitude;
  geocoder.geocode({
    'address': address
  }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      latitude = results[0].geometry.location.lat();
      longitude = results[0].geometry.location.lng();
      callback(latitude, longitude);
    }
  });
}
latLong(postcodeValue, function(lat, lon) {
  console.log(lat);
  console.log(lon);
});
var options = {
  mapTypeControlOptions: {
    mapTypeIds: [ 'Styled']
  },
  center: new google.maps.LatLng(latLong),
  zoom: 12,
  mapTypeId: 'Styled',
  disableDefaultUI: true,
  draggable: false,
  disableDoubleClickZoom: true
};
var div = document.getElementById('map');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles);
map.mapTypes.set('Styled', styledMapType);

有谁能帮忙吗?

您所能做的就是读取哈希。示例:mywebsite.com#9000。散列右边的任何东西都适合用作javascript的变量。

我添加了一些链接到3个比利时城市。href="?1#1000",href="?2#8000"。注意:添加"?1"answers"?2"只是为了确保URL不同(#的左边),否则web浏览器不会更改页面。

我禁用了你关于地图样式的几行代码。随意添加背面。

看第9行,改变国家。

<html>
<head>
  <title>Update google map from postcode on page load</title>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script>
  function initialize() {
    // read the hash in the url
    var postcodeValue = window.location.hash.substring(1) || 1000 ;// example:  mywebsite.com?p=maps#1000  ;  1000 is default, if no postal code is in the url
    postcodeValue += ', BE';  // probably best to add a country
    var div = document.getElementById('map');
    var map;
    latLong(postcodeValue, function(lat, lon) {
      var options = {
        mapTypeControlOptions: {
          // mapTypeIds: [ 'Styled']
        },
        center: new google.maps.LatLng(lat, lon),
        zoom: 12,
        // mapTypeId: 'Styled',
        disableDefaultUI: true,
        draggable: false,
        disableDoubleClickZoom: true
      };
      map = new google.maps.Map(div, options);
    });
    // var styledMapType = new google.maps.StyledMapType(styles);
    // map.mapTypes.set('Styled', styledMapType);
    function latLong(location, callback) {
      var geocoder = new google.maps.Geocoder();
      var address = location;
      var longitude;
      var latitude;
      geocoder.geocode({
        'address': address
      }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          latitude = results[0].geometry.location.lat();
          longitude = results[0].geometry.location.lng();
          callback(latitude, longitude);
        }
      });
    }
  }
  google.maps.event.addDomListener(window, 'load', initialize);
  </script>
  <style>
    #map {
      height: 400px;
    }
  </style>
</head>
<body>
  <a href="?1#1000">Brussels</a>
  <a href="?2#8000">Bruges</a>
  <a href="?3#9000">Ghent</a>
  <div id="map">
</body>
</html>
  1. 从查询字符串中读取"postcode"参数
  2. 把它传给地理编码器
  3. 用它来设置地图的中心/缩放(并不是说下面的代码片段设置了一个默认地址,即纽约州纽约市,如果邮政编码的地理编码失败,该地址将保留

var map = null;
function initialize() {
  var options = {
    /* mapTypeControlOptions: {
      mapTypeIds: ['Styled']
    }, */
    center: new google.maps.LatLng(0, 0),
    zoom: 4,
    // mapTypeId: 'Styled',
    disableDefaultUI: true,
    draggable: false,
    disableDoubleClickZoom: true
  };
  var div = document.getElementById('map');
  map = new google.maps.Map(div, options);
  // var styledMapType = new google.maps.StyledMapType(styles);
  // map.mapTypes.set('Styled', styledMapType);
  // default location
  codeAddress("New York, NY");
  
  // If there are any parameters at eh end of the URL, they will be in  location.search
  // looking something like  "?marker=3"
  // skip the first character, we are not interested in the "?"
  var query = location.search.substring(1);
  // split the rest at each "&" character to give a list of  "argname=value"  pairs
  var pairs = query.split("&");
  for (var i = 0; i < pairs.length; i++) {
    // break each pair at the first "=" to obtain the argname and value
    var pos = pairs[i].indexOf("=");
    var argname = pairs[i].substring(0, pos).toLowerCase();
    switch (argname) {
      case "postcode":
        var value = pairs[i].substring(pos + 1);
        codeAddress(value);
      default:
        break;
    }
  }
}
google.maps.event.addDomListener(window,'load',initialize);
function codeAddress(location) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': location
  }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0].geometry.viewport) 
        map.fitBounds(results[0].geometry.viewport);
      else if (results[0].geometry.bounds)
        map.fitBounds(results[0].geometry.bounds);
      else map.setCenter(results[0].geometry.location);
    }
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>