Karvy1
Karvy1

Reputation: 1055

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

I using a html form to input a zip-codes (PortZip)

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

and I want pass the zip-code value to java script code line

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

Currently the java script code line takes LatLng values manually. How do I change the java script code line to take the zip-code value?

Upvotes: 0

Views: 824

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Use the Geocoder to translate addresses (or zipcodes) into geographic coordinates that can be used in the Google Maps Javascript API.

code snippet:

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>

Upvotes: 1

Related Questions