简体   繁体   English

在页面加载时从邮政编码更新Google地图

[英]Update google map from postcode on page load

I'm trying to generate a map on page load from a postcode value. 我正在尝试根据邮政编码值在页面加载时生成地图。

To do this I'm geocoding the dynamic postcode that is given and I have got it to give me a longitude and latitude from that dynamic postcode. 为此,我对给定的动态邮政编码进行了地理编码,并获得了该动态邮政编码的经度和纬度。

The postcode is sent from a form on a previous page and is stored in the url like so: 邮编是从上一页的表单发送的,并像下面这样存储在url中:

url.com?postcode=XXXXXX

The problem now is how do I join up the longitude and latitude values to pass through into the following: 现在的问题是如何将经度和纬度值结合起来以传递给以下内容:

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

This is the JS I have at the moment: 这是我目前拥有的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);

Anyone able to help with this please? 有人能帮忙吗?

What you can do, is read the hash. 您能做的就是读取哈希。 Example: mywebsite.com#9000 . 例如:mywebsite.com#9000。 Any thing to the right of the hash is ideal to be used as variables for javascript. 哈希值右边的任何东西都理想用作JavaScript变量。

I added some links to 3 Belgian cities. 我添加了一些指向3个比利时城市的链接。 href="?1#1000" , href="?2#8000". href =“?1#1000”,href =“?2#8000”。 Notice: the "?1" and "?2" are just added to make sure the URL is different (left of the #), otherwise the web browser won't change the page. 注意:仅添加了“?1”和​​“?2”以确保URL不同(#的左侧),否则Web浏览器将不会更改页面。

I disabled a few of your lines of code regarding the map style. 我禁用了一些有关地图样式的代码行。 Feel free to add the back. 随时添加背面。

Look at line 9 to change the country. 查看第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. read the "postcode" parameter from the query string 从查询字符串中读取“邮政编码”参数
  2. pass that to the geocoder 将其传递给地址解析器
  3. use that to set the center/zoom of the map (not that the code snippet below sets a default address of New York, NY that will remain if the geocode of the postcode fails. 使用它来设置地图的中心/缩放(不是下面的代码段设置默认地址纽约,NY,如果邮政编码的地址解析失败,该默认地址将保留)。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM