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

时间:2014-10-30 15:02:34

标签: javascript google-maps google-geocoder

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

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

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

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);

有人能帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

你能做什么,是读哈希。示例:mywebsite.com#9000。哈希右边的任何东西都非常适合用作javascript的变量。

我添加了3个比利时城市的链接。 HREF =" 1#1000" ,href ="?2#8000"。注意:"?1"和"?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 :(得分:0)

  1. 阅读&#34;邮政编码&#34;查询字符串中的参数
  2. 将其传递给地理编码器
  3. 用它来设置地图的中心/缩放 (并不是下面的代码片段设置纽约,纽约的默认地址,如果邮政编码的地理编码失败,它将保留。
  4. &#13;
    &#13;
    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);
        }
      });
    }
    &#13;
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
    }
    &#13;
    <script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
    <div id="map"></div>
    &#13;
    &#13;
    &#13;