Google maps geocoding with bounds - google-maps

With the following code when I get a result back, I don't appear to get the full address components of the result back, which we are using with our other services to determine various things.
As soon as I take the bounds out, it works fine. But I still need it restricted to the bounds.
Why is this? and how can I solve the issue?
CODE:
_geocoder.geocode(_.extend(position, {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
}), function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
_lastResults = results;
deferred.resolve(results);
} else {
deferred.reject('Geocode was not successful for the following reason: ' + status);
}
});

To add the bounds to the GeocoderRequest, it goes inside the request object:
var data = {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
};
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(data.bounds.south, data.bounds.west),
new google.maps.LatLng(data.bounds.north, data.bounds.east));
geocoder.geocode({
address: "London",
bounds: bounds
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
Note however:
Optional parameters:
bounds — The LatLngBounds within which to bias geocode results more prominently. The bounds parameter will only influence, not fully restrict, results from the geocoder. (For more information see Viewport Biasing below.)
proof of concept fiddle
code snippet:
function initialize() {
var 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
});
var data = {
bounds: {
west: -25.806884999999966,
east: 16.380615000000034,
south: 48.98742739340465,
north: 60.16884190739975
}
};
var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(data.bounds.south, data.bounds.west), new google.maps.LatLng(data.bounds.north, data.bounds.east));
var rectangle = new google.maps.Rectangle({
map: map,
bounds: bounds
});
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address: "London",
bounds: bounds
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Related

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>

get the elevation of a googlemaps' marker

I try to get the elevation of a point on a map, but the elevation function proposed by the googlemaps' API doesn't work and I don't know why.
It seems that the programm don't even get through the function.
Here my function :
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': gmarkers[0].getPosition()};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + "mètres";
}
} });
I get a javascript error with your code: Uncaught InvalidValueError: in property locations: not an Array
The locations property in the LocationElevationRequest must be an array.
from the documentation for google.maps.LocationElevationRequest object specification
An elevation request sent by the ElevationService containing the list of discrete coordinates (LatLngs) for which to return elevation data.
Properties
locations Type: Array
The discrete locations for which to retrieve elevations.
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
proof of concept fiddle
code snippet:
var gmarkers = [];
function initialize() {
var 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
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
gmarkers.push(marker);
var elevationService = new google.maps.ElevationService();
var requestElevation = {
'locations': [gmarkers[0].getPosition()]
};
elevationService.getElevationForLocations(requestElevation, function(results, status) {
if (status == google.maps.ElevationStatus.OK) {
if (results[0]) {
document.getElementById('denivele_circuit').value = parseFloat(results[0].elevation.toFixed(1)) + " mètres";
}
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="denivele_circuit" />
<div id="map_canvas"></div>

Zooming and centering the geocoded place using google maps api

I am working with the google maps api for one of my application. I have a textbox in which the user enters place name. It should geocode the users place name given in the textbox and zoom and center to that geocoded place name. I am successful in the geocoding but zooming and centre is not as expected. The code and output snapshot is provided.The black rectangle in the image is the place name that was geocoded based on the user input in the textbox. But zooming and centering is somewhere in the corner of the map. I want it to make the geocoded place name in the center of map.
var mapProp = {
center: x,
zoom: 4,
disableDefaultUI: true,
mapTypeId: layer,
mapTypeControlOptions: {
mapTypeIds: [layer]
}
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
Place_name_filter is the variable which holds the the place name entered in the textbox.
Output_Snapshot_for_the_above_code
Expected_Output
To zoom to a result from the geocoder use map.fitBounds and the .geometry.viewport (or geometry.bounds) LatLngBounds in the response.
code snippet:
function initialize() {
var mapProp = {
center: {
lat: 25,
lng: -90
},
zoom: 4,
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapProp);
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
var place_name_filter = "Abilene, TX";
geocoder.geocode({
'address': place_name_filter
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert(place_name_filter + " not found");
console.log("status : ", status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googlemaps {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googlemaps"></div>

Google Map API3 return no map?

Im trying to make marker on google map, based on adress, but maps is showing no data?
Here is my example
$(document).ready(function() {
/* google maps */
google.maps.visualRefresh = true;
var geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 14, // set the zoom level manually
zoomControl: false,
scaleControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map;
function initialize() {
var address = $('#map').text(); /* change the map-input to your address */
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: address,
map: map,
position: results[0].geometry.location,
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
} else {
alert("No results found");
}
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
});
HTML
<p id="map">
Vojvode Dobrnjca, Belgrade
</p>
<div id="map-canvas"></div>
You had missed center in mapOptions.
And you should create geocoder variable in initialize function.
Please refer this. I had shown your map.

Google Maps Geocoding and ploting several locations

I am trying to implement a script that will geocode and plot all the locations of an array into a map. I am stack because I cannot get the map to fit all the markers added in the screen. I lost many hours trying several methods and this what I came up to:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script>
var geocoder;
var map;
var markersArray = [];
var bounds;
//plot initial point using geocode instead of coordinates (works just fine)
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds ();
latlang = geocoder.geocode( { 'address': '5th Avenus New Yort'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
var myOptions = {
center: latlang,
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
plotMarkers();
}
var locationsArray = [
['Google Official','1600 Amphitheatre Parkway, Mountain View, USA'],
['Google 1','112 S. Main St., Ann Arbor, USA'],
['Google 2','10 10th Street NE, Suite 600 USA']
];
function plotMarkers(){
for(var i = 0; i < locationsArray.length; i++){
console.log(locationsArray[i][1]);
//codeAddresses(locationsArray[i]);
}
//map.fitBounds (bounds);
}
function codeAddresses(address){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend (new google.maps.LatLng (results[0].geometry.location.ib,results[0].geometry.location.hb));
//console.log(bounds);
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas" style="width: 100%; height: 700px;"></div>
</body>
</html>
Can somebody give me a hand on this because it seems that I am going to stick with this version forever.
I have the following to goals:
1. Bound the displayed map so that all markers placed in the map will be displayed.
2. Add infoWindow with the name of the location.
I would appreaciate any help!
Regards to all of you,
Nick
What you need to do is extend your bounds object as you add each marker. Then after adding them all, call fitBounds to redraw the map to the appropriate zoom level for that bounds object.
Add an InfoWindow within the loop as you create your markers, bound to each marker. This worked for me:
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow = new google.maps.InfoWindow({
content: ''
});
//plot initial point using geocode instead of coordinates (works just fine)
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds ();
var myOptions = {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode( { 'address': '5th Avenus New Yort'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
plotMarkers();
}
var locationsArray = [
['Google Official','1600 Amphitheatre Parkway, Mountain View, USA'],
['Google 1','112 S. Main St., Ann Arbor, USA'],
['Google 2','10 10th Street NE, Suite 600 USA']
];
function plotMarkers(){
var i;
for(i = 0; i < locationsArray.length; i++){
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address){
geocoder.geocode( { 'address': address[1]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(address[0]);
infowindow.open(map, this);
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);