show postal code/zip code bounds on google map - google-maps

I would like to mark the outline (bounds) of a postal code on a map. With google maps API, I can send a postal code or address and get back log/lat, then place a icon on a map. Now I would like to make a box or polygon around the entire area covered by the postal code. Is there an API or method to do this? I could use google maps or other service if available.
Api to get lat/lon of postal code...
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK){
var pcode = results[0].address_components[0].long_name;
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
}

geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pcode = results[0].address_components[0].long_name;
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
//do whatever you want above then call the displayBounds function
displayBounds(results[0].geometry.bounds);
}
});
function displayBounds(bounds) {
var rectangleOptions = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWeight: 3,
bounds: bounds
}
var rectangle = new google.maps.Rectangle(rectangleOptions);
rectangle.setMap(map); //map being your google.maps.Map object
}
This way you can display the bounds on the map. Make sure you get the geometry.bounds on your results though, since it's not always the case.

DisplayZipCodeArea(results[0].geometry.bounds, resultsMap);
function DisplayZipCodeArea(bounds, resultsMap) {
var rectangleOptions = {
strokeColor: '#0000ff',
strokeOpacity: 0.5,
strokeWeight: 3,
bounds: bounds
}
var rectangle = new google.maps.Rectangle(rectangleOptions);
rectangle.setMap(resultsMap); //map being your google.maps.Map object
}

Related

Google Maps API Geocode - return GPS coordinations [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map

Google Streetview API returns a different view than google.com/maps. Any workaround?

So I noticed that google.com/maps provides a different StreetView than my Streetview API with the combination of geolocator.
To show you an example, we will use the following address:
2510 Cherry Valley Blvd Dallas, TX 75241
When getting coordinates of this address, I use the following geocode api:
http://maps.google.com/maps/api/geocode/json?address=2510+Cherry+Valley+Blvd+Dallas,+TX+75241
It returns the following location:
{ lat: 32.6432887, lng: -96.7823027 }
I then use these coordinates in my Google Streetview API.
However, when I go on google.com/maps, enter the same address and go to streetview, it ends up with slightly different coordinates that better represent the front face of the business address. In this case, the coordinates that it uses are the following:
{lat: 32.6439611, lng: -96.7825014}
https://www.google.com/maps
Below are two images (first the result with Google Maps API, and the second result is with google.com/maps.
How do I make sure that the view returned on my page with Google Maps API is exactly the same as that on google.com/maps?
My client needs this. Any ideas on how to adjust geolocator API or Google Maps API would be greatly appreciated.
My Google Maps API returns the following image (for some reason the view is on the adjecent street, and as a result is slightly incorrect):
Google.com/maps returns the following image (address says 2519 Cherry Valley even though I searched for 2510 Cherry Valley). Google api seems to adjust geolocation for more accurate view.
One option is to snap the streetview using the DirectionsService, which returns the place you would drive to.
proof of concept fiddle
code snippet:
var map;
var sv = new google.maps.StreetViewService();
var geocoder = new google.maps.Geocoder();
var directionsService = new google.maps.DirectionsService();
var panorama;
var address;
function initialize() {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
var myOptions = {
zoom: 15,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
address = "2510 Cherry Valley Blvd Dallas, TX 75241";
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatLng = results[0].geometry.location;
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
map.setCenter(myLatLng);
// find a Streetview location on the road
var request = {
origin: address,
destination: address,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, directionsCallback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
sv.getPanoramaByLocation(myLatLng, 50, processSVData);
// getPanoramaByLocation will return the nearest pano when the
// given radius is 50 meters or less.
google.maps.event.addListener(map, 'click', function(event) {
sv.getPanoramaByLocation(event.latLng, 50, processSVData);
});
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = new google.maps.Marker({
position: data.location.latLng,
draggable: true,
map: map,
title: data.location.description
});
panorama.setPano(data.location.pano);
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, myLatLng);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
} else {
alert("Street View data not found for this location.");
}
}
function geocoderCallback(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
sv.getPanoramaByLocation(latlng, 50, processSVData);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
};
function directionsCallback(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var latlng = response.routes[0].legs[0].start_location;
map.setCenter(latlng);
sv.getPanoramaByLocation(latlng, 50, processSVData);
} else {
alert("Directions service not successfull for the following reason:" + status);
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body {
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="pano" style="width: 100%; height: 400px;"></div>
<div id="map_canvas" style="width: 100%; height: 400px;"></div>

Could not centralise the google map after location search in angular 2

I have a input field and a button. On click of button the location whatever written in the input field will set a marker in google map. I am able to locate a marker in map. But it wont appear in the centre. In fact map will stay constant whatever the location you search.
getAddress(place:Object) {
this.markers = [];
var address = this.step1Data.map_address;
if (!address) return false;
var geocoder = new google.maps.Geocoder();
var that = this;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
that.markers.push({
lat: lat,
lng: lng,
label: 'A',
draggable: false
})
that._googleMapsApi.setCenter(location);
}
});
}
setCenter() method is not working here. May I know the reason. googleMapsApi is imported from angular2-google-maps/core.

Google Maps API - Radius search for markers using Places?

I have set up a Google Map using API v3. The map has a number of markers with infoboxes attached. I am looking to set up a search box outside of the map for the user to input an address and then have the nearest markers returned based on the distance away (such as a radius search).
From the API documentation I think I need to uses the Places services. Can anyone point me in the right direction?
To do a radius search with the API, use the Geometry Library google.maps.geometry.spherical.computeDistanceBetween method to calculate the distance between each marker and the geocoded result from the address. If that distance is less than the requested radius, show the marker, else hide it.
code assumes:
array of google.maps.Markers called gmarkers
google.maps.Map object called map
function codeAddress() {
var address = document.getElementById('address').value;
var radius = parseInt(document.getElementById('radius').value, 10)*1000;
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
});
if (circle) circle.setMap(null);
circle = new google.maps.Circle({center:marker.getPosition(),
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<gmarkers.length;i++) {
if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) {
bounds.extend(gmarkers[i].getPosition())
gmarkers[i].setMap(map);
} else {
gmarkers[i].setMap(null);
}
}
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
example

Find out distance between two points using Google map API based on medium (Road,Air,Ship)? [duplicate]

I have used the google map API to plot a way point on google map
I referred to the the following page:
https://developers.google.com/maps/documentation/javascript/directions
'Using Waypoints in Routes section' and modified it a bit so as to plot only 3 points on the map.
The following is my javascript code.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var initialloc = new google.maps.LatLng(12.971599, 77.594563);
var mapOptions = {
zoom : 6,
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : initialloc
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var lat = new Array();
var lon = new Array();
var start = new google.maps.LatLng(12.971599,77.594563);
var mid = new google.maps.LatLng(12.971558,77.594552);
var end = new google.maps.LatLng(12.971558,77.594552);
var waypts = [];
waypts.push( {
location : mid,
stopover : true
});
var request = {
origin : start,
destination : end,
waypoints : waypts,
optimizeWaypoints : true,
travelMode : google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(
request,
function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
}
});
}
which works perfectly fine if the 3 locations are within same country, ie they have a road map.
My question is how to plot the map when the location are in different continents eg India and Australia?
Can anyone please help.
Thanks in Advance.
The problem is not about different continents, but whether the routing engine's database has information about all the countries between your start and endpoints, including car ferries. You can see that the same occurs in maps.google.com . Here's an intercontinental route from Europe to India, but if you try to move the B marker to the US or Canada, it doesn't get a route because it doesn't know a ferry across the Atlantic.
You can see what countries have coverage in this spreadsheet.