Reputation: 5835
I use the Google Maps Geocoding API. When I pass in the zip 75116, I get Paris, France. Specifically: 48.8585799, lon = 2.284701700000028. I should get Duncanville, Texas.
This is the URL I'm using:
https://maps.googleapis.com/maps/api/js?sensor=true&client=CLIENT-NAME&v=3.21
I tried appending this to the URL but it didn't work:
&components=country:US
Upvotes: 0
Views: 381
Reputation: 1
You have to use geocoder for getting address using zipcode:
Here sample code is provided:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtRkkKYEMY8CX1IbWbsAYLqzh-_pecegg&callback=initMap"
async defer></script>
<script>
var map;
function initMap() {
var geocoder = new google.maps.Geocoder();
var myLatlng = new google.maps.LatLng(48.8585799, 2.284701700000028);
var mapOptions = {
center : myLatlng,
zoom : 17
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder.geocode({
address : '75116',
componentRestrictions: {
country: 'us'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
// alert("no asdsd");
}
});
}
</script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
Upvotes: 0
Reputation: 11
I can see two locations in the response for the "75116" geocoding request: Paris and Duncanville. Apparently, "75116" is not a unique location identifier. Requesting "US 75116" results in the single expectable location.
Upvotes: 0
Reputation: 117314
In the maps-Javascript-API the componentRestrictions must be passed along with the geocoderRequest
function init() {
var map = new google.maps.Map(document.getElementById("map-canvas"), {
center: new google.maps.LatLng(0.0),
zoom: 13
}),
geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: '75116',
componentRestrictions: {
country: 'us'
}
},
function(r, s) {
if (s == google.maps.GeocoderStatus.OK) {
map.setCenter(r[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: r[0].geometry.location
});
} else {
window.alert('Geocode was not successful for the following reason: ' + s);
}
}
);
}
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map-canvas"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&callback=init">
</script>
Upvotes: 2