google maps api v3 places autocomplete only for selected city - google-maps

when user starts to type city, autosuggest only suggests cities within 50 miles of tampa, FL (or anything else )
var southWest = new google.maps.LatLng( 28.3914,-81.936035 );
var northEast = new google.maps.LatLng( 28.3914,-81.936035 );
var hyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );
var options = {
bounds: hyderabadBounds,
types: ['geocode'],
componentRestrictions: { country: 'us' }
};
var input1 = document.getElementById('search_header');
var autocomplete = new google.maps.places.Autocomplete(input1,options);

you are using the same LatLng for NorthEast and SouthWest of hyderabadBounds, use a LatLngBounds-object that encompasses the desired area, e.g.:
bounds: new google.maps.Circle({center:new google.maps.LatLng( 28.3914,-81.936035 ),
radius:50000}).getBounds()
Note: there is no guarantee that the Automplete restricts the results to the given bounds

Related

Restrict Google Autocomplete results using bounds option

I am trying to use Google Places Autocomplete and restrict the results to a specific city in Canada, namely Toronto. I am aware that using the componentRestrictions option will allow me to restrict the results to Canada by using componentRestrictions: {country: 'CA'}. In order to further restrict the results to Toronto, I understand that I have to add the bounds property to the options object. The LatLngBounds expects south-west and north-east corners, which are also referred to as bottom-left and top-right corners.
I found this sample code which implements this strategy for the City of Hyderabad in Pakistan and it works perfectly:
var input = document.getElementById('searchTextField');
var southWest = new google.maps.LatLng( 25.341233, 68.289986 );
var northEast = new google.maps.LatLng( 25.450715, 68.428345 );
var HyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );
var options = {
bounds: HyderabadBounds,
types: ['address'],
componentRestrictions: { country: 'PK' }
};
var autocomplete = new google.maps.places.Autocomplete( input, options);
When I try to modify the code to work for an area in Canada, for some reason it is not working. Here is my modified code:
var input = document.getElementById('searchTextField');
var southWest = new google.maps.LatLng( 43.941160, -78.895187 );
var northEast = new google.maps.LatLng( 42.946172, -81.296577 );
var TorontoBounds = new google.maps.LatLngBounds( southWest, northEast );
var options = {
bounds: TorontoBounds,
types: ['address'],
componentRestrictions: { country: 'CA' }
};
var autocomplete = new google.maps.places.Autocomplete( input, options);
The only thing different about my modified code is the country designation CA and the LatLng coordinates which I believe to be correct. I double-checked my coordinates and the southWest coordinate refers to a location southWest of Toronto and the northEast coordinate refers to a location northEast of Toronto, so I would expect that these should work. Although my results are properly restricted to Canada, they are not within my bounds as specified by the LatLng coordinates.
Can anyone see what I might be doing wrong?
Your northEast and southWest points are named incorrectly. Change their names:
var northEast = new google.maps.LatLng(43.941160, -78.895187);
var southWest = new google.maps.LatLng(42.946172, -81.296577);
If I set them to:
var northEast = new google.maps.LatLng(43.941160, -78.895187);
var southWest = new google.maps.LatLng(42.946172, -81.296577);
The bounds object is correct.
proof of concept fiddle
code snippet:
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13
});
var input = document.getElementById('searchTextField');
var northEast = new google.maps.LatLng(43.941160, -78.895187);
var southWest = new google.maps.LatLng(42.946172, -81.296577);
var SWmark = new google.maps.Marker({
map: map,
position: southWest,
title: southWest.toUrlValue(6),
label: "SW"
});
var NEmark = new google.maps.Marker({
map: map,
position: northEast,
title: northEast.toUrlValue(6),
label: "NE"
});
var TorontoBounds = new google.maps.LatLngBounds(southWest, northEast);
var rectangle = new google.maps.Rectangle({
map: map,
bounds: TorontoBounds
});
map.fitBounds(TorontoBounds);
var options = {
bounds: TorontoBounds,
types: ['address'],
componentRestrictions: {
country: 'CA'
}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="pac-container">
<input id="searchTextField" type="text" placeholder="Enter a location">
</div>
<div id="map"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

Automatically show street view map when inputting an address

I want to put in a street address, and have it programatically determine the coordinates and heading for the purposes of generating a street view map. instantstreetview.com does this, so I know it can be done. From the docs:
function initialize() {
var fenway = {lat: 42.345573, lng: -71.098326};
var map = new google.maps.Map(document.getElementById('map'), {
center: fenway,
zoom: 14
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: fenway,
pov: {
heading: 34,
pitch: 10
}
});
map.setStreetView(panorama);
}
Problem is, I don't know the heading of the address I want. Is there a simple way to achieve this?
You may want to look into getting the LatLng from the StreetViewLocation of the StreetViewPanorama rendered to compute the heading using the computeHeading() in the Geometry library in the Javascript API.
Take a look at this sample JSBin. I've created two Street View divs with the lat/lngs of two addresses across the street from each other. Notice that, regardless of the lat/lng, the same pano is returned, but there is no heading information, so the view is the same:
Now, look at this this modified JSBin. After computing the heading based on the StreetViewLocation.latLng of the panorama and lat/lng of the addresses passed into StreetViewService and using that as the pov for the panoramas, the correct Street View imagery is shown for each address:
The pertinent code:
var ll = new google.maps.LatLng(37.435292,-122.129517);
var svs = new google.maps.StreetViewService();
svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
var pos = data.location.latLng;
var head = google.maps.geometry.spherical.computeHeading(pos, ll);
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
pano: data.location.pano,
pov: {heading: head, pitch:0}
});
});
EDIT: Adding another simple JSBin showing the use of the Geocoder to get the LatLng for the addresses: Pertinent code:
var ll;
var geocoder = new google.maps.Geocoder();
var svs = new google.maps.StreetViewService();
geocoder.geocode({address: "757 Moreno Ave Palo Alto, CA"}, function(results, status) {
if (status == 'OK') {
ll = results[0].geometry.location;
svs.getPanorama({location: ll, preference: 'nearest'}, function(data, status){
var pos = data.location.latLng;
var head = google.maps.geometry.spherical.computeHeading(pos, ll);
panorama = new google.maps.StreetViewPanorama(
document.getElementById('street-view'),
{
pano: data.location.pano,
pov: {heading: head, pitch:0}
});
});
}
});

Search By Google Place Autocomplete and get the distance from google matrix API

I developed the code for our website that a user can autocomplete the location field using google places API and calculate distance from google matrix API using the lat-long.
1- My Code for autocomplete the location
<script>
var frm_ggl_dd = 1;
function initMap() {
var options = {
/*types: ['(cities)'],
regions:['(locality,sublocality,postal_code)'],*/
componentRestrictions: {country: "in"}
};
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 28.6315, lng: 77.2167},
zoom: 13
});
var input = /** #type {!HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input,options);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
frm_ggl_dd = 1;
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
/*setting hidden field value so that have idea getting from google database*/
/* $('#frmGoogleDB').val(1); */
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDem6tqqXGpyvFNmgIdVIsmg3VlPZxAwe8&libraries=places&callback=initMap" async defer></script>
The problem is the above code is- it show the result with state and country like Eden Garden, Kolkata, West Bengal, India. My requirement is to show the result as Eden Garden, Kolkata and fill the input field as Eden Garden, Kolkata.
2- Calculate the Distance between this autocomplete place and a seller's lat-long . below is the code - $google_landmark refer to autocomplete google places
$api_url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($google_landmark).'&sensor=false';
$geo = file_get_contents($api_url);
$geoDecoded = json_decode($geo, true);
if ($geoDecoded['status'] = 'OK') {
$latitude = $geoDecoded['results'][0]['geometry']['location']['lat'];
$longitude = $geoDecoded['results'][0]['geometry']['location']['lng'];
//echo $latitude.'-'.$longitude.'<br/>';
$distance = $this->getMaxDistance($latitude, $longitude, $arrVenLatLng);
}
public function getMaxDistance($CustLatitude, $CustLongitude, $arrVenLatLng){
$arrDistance = array();
for($i=0; $i<count($arrVenLatLng); $i++){
$geoDist = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='.$CustLatitude.','.$CustLongitude.'&destinations='.$arrVenLatLng[$i]['lat'].','.$arrVenLatLng[$i]['long'].'&key=AIzaSyBV8Dbe9bMAK35VmLUSN30xXivN7ICVvsg');
$geoDist = json_decode($geoDist, true);
if($geoDist['status'] = 'OK'){
$arrDistance[] = $geoDist['rows'][0]['elements'][0]['distance']['value']/1000;
}
}
return ceil(max($arrDistance));
}
The google places show a result Eden Garden, Kolkata, West Bengal, India
but the
'https://maps.googleapis.com/maps/api/geocode/json?address=Eden Garden, Kolkata, West Bengal, India&sensor=false';
not return a result. please suggest what is the problem with my code or logic.
Thanks
What I have read from your code above, you have a fixed position:
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 28.6315, lng: 77.2167},
zoom: 13
});
It might be the problem, that your lat and lng cannot get updated.
-Paul
Google geocoder API works effective only when it is given exact addresses. The problem with your second call is even though Eden Garderns, Kolakata, West Bengal, India is from an auto complete value provided by the Google places API, this place actually has an adress as Churchgate, Mumbai, Maharashtra 400020, India. If you pass this actual address to the Google geocoder API then you will be able to retrieve the lat/long.Instead of directly taking the auto fill value get the address from the place selected. (Google place API has a place detail request and you can get complete address through that).

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.

Google Maps : Show Map Via Address

I have this Code To show map on a page
var _map = new GMap2($get("gmap"));
var _latLng = new GLatLng(lat, lng);
_map.setCenter(_latLng, 11);
_map.addControl(new GLargeMapControl());
_map.addControl(new GMapTypeControl());
var _icon = new GIcon(G_DEFAULT_ICON);
var marker = new GMarker(_latLng);
_map.addOverlay(marker);
But I do Not have GeoCode for Some Address.
How can I show Map via Address Only.
You use the GeoCoder to get the address into latitude and longitude first, and then use that.
Here's an example of how to geocode an address.