Google API:如何将邮政编码值传递到JavaScript代码中

Google API: How to pass zip-code value into the JavaScript code

本文关键字:JavaScript 代码 值传 邮政编码 API Google      更新时间:2023-09-26

我使用html表单输入邮政编码(PortZip)

Port ZipCode:<br>
<input type="text" id="PortZip" value="31402">

和我想传递邮编值到java脚本代码行

var point1 = new google.maps.LatLng(-33.8975098545041,151.09962701797485);

目前java脚本代码行手动获取LatLng值。如何更改java脚本代码行以获取邮政编码值?

使用Geocoder将地址(或邮政编码)转换为可在Google Maps Javascript API中使用的地理坐标。

代码片段:

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  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
    });
  codeAddress(document.getElementById('PortZip').value);
}
google.maps.event.addDomListener(window, "load", initialize);
function codeAddress(address) {
  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);
    }
  });
}
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
Port ZipCode:
<br>
<input type="text" id="PortZip" value="31402">
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>