Google places search box without map? - google-maps

I want to implement a feature where people will be able to change their location. For that I want to use google places api. Now what I want is a search box and when someone inputs a town/place it will search google places and come up with results. Once location is choosen it will give me lat and lng of that place. Is that possible to do without the map?
thanks

You can use the Google Maps Places Autocomplete to get an accurate address, and then after you successfully get an address you can geocode it to get the lat and lng.
Like this:
function codeAddress(address) {
geocoder.geocode({ 'address': address}, function(results, status) {
if (status == 'OK') {
alert(results[0].geometry.location); // This is the lat and lng
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Check this working example: https://jsbin.com/pejagub/edit?html,js,output
I also inserted here the code snippet incase the jsbin is not working
var placeSearch, autocomplete, geocoder;
function initAutocomplete() {
geocoder = new google.maps.Geocoder();
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
autocomplete.addListener('place_changed', fillInAddress);
}
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == 'OK') {
// This is the lat and lng results[0].geometry.location
alert(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function fillInAddress() {
var place = autocomplete.getPlace();
codeAddress(document.getElementById('autocomplete').value);
}
#autocomplete {
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" type="text" />
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&libraries=places&callback=initAutocomplete" async defer></script>
</body>
</html>

Sorry for being late. You may find your answer here:
https://developers.google.com/maps/documentation/javascript/places-autocomplete#video
```
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('searchTextField');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
```
No need for map object reference just pass the bounds.

Related

Google Maps Geocoding API returns undesired result after being passed zip code

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
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>
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.
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>

Google map API theme option page not displaying

I'm having some issues with the integration of a google map in my web site which can geocode an address before displaying the map with the correct location.
So i have a script (it worked when i was in localhost but since i put the web site online nothing happens) :
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
var firstLoc;
function findAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address' : document.getElementById('address_field').value},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
firstLoc = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map-location"),
{
center: firstLoc,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert('Geocode failed: ' + status);
}
}
);
}
google.maps.event.addDomListener(window, 'load', findAddress);
</script>
I put an address in a field in my theme option page then i register the value and put it in a hidden input in my front-end and try to get it with geocoder.geocode( { 'address' : document.getElementById('address_field').value}
Seems to have a problem with geocoding, i tested with a simple script with a fix position and it showed fine.
In case you need it this is how i display the map in the front-end :
<div class="contact-map">
<div id="map-location"></div>
<form class="address-hidden">
<?php echo "<input id='address_field' type='text' value= '{$content_options['geolocal_setting']}'/>"?>
</form>
</div>

How to get the users location using google maps v3

I have been trying to get the users location using the map v3 and show the path from there location to a fixed destination. But i had no luck finding a solution to get the users location, i have read the API but couldn't figure out anything checked all the examples still the same . hope some one can help me Thanx.
Solution:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});
google.loader.ClientLocation only gives a very approximate estimate as to the user's location.
Best choice is to use that as a fallback if HTML5 geolocation is not present, or not allowed by the user.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(p) {
//get position from p.coords.latitude and p.coords.longitude
},
function() {
//denied or error
//use google.loader.ClientLocation
}
);
} else {
//use google.loader.ClientLocation
}
jQuery('#map_canvas').gmap({ 'zoom':2,'center':new google.maps.LatLng(39.809734,-98.55562), 'callback': function() {
var self = this;
self.getCurrentPosition(function(position, status) {
if ( status === 'OK' ) {
clientlat = position.coords.latitude;
clientlon = position.coords.longitude;
var clientlatlng = new google.maps.LatLng(clientlat, clientlon);
}
});
}});

How to generate url link to google map from nearbySearch() results?

With the example below,
https://google-developers.appspot.com/maps/documentation/javascript/examples/place-search
By using nearbySearch one of the place return is "John St Square Supermarket".
How do i generate a url to show "John St Square Supermarket" in full google maps?
Right now i'm generating by appending the latitude and longitude into "http://maps.google.com/?q=" which become something like http://maps.google.com/?q=123,456
but it won't show the place's name and the correct marker.
I then tried with http://maps.google.com/?q=John St Square Supermarket
Working good... until i stumble into a place name with multiple locations. For example,
http://maps.google.com/?q=SK%20Dato%27%20Abu%20Bakar
It shows multiple location but i only need one which i already know what it's latitude and longitude is.
You can add the Latitude and Longitude to the URL using the parameter ll:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471
You can also specify a default zoom level for the user using the paremeter z:
https://maps.google.com/?q=pizza+hut&ll=-33.867701,151.208471&z=12
PlacesResult.url property stands for the url of Google Places.
https://developers.google.com/maps/documentation/javascript/reference#PlaceResult
So you can do like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Place Search</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<style>
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script>
var map;
var infowindow;
var service;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId : google.maps.MapTypeId.ROADMAP,
center : pyrmont,
zoom : 15
});
var request = {
location : pyrmont,
radius : 500,
types : ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map : map,
position : place.geometry.location,
reference : place.reference,
name : place.name
});
google.maps.event.addListener(marker, 'click', onMarker_clicked);
}
function onMarker_clicked() {
var marker = this;
service.getDetails({
reference : marker.get("reference")
}, function(result) {
var html = marker.get("name");
if (result && "url" in result) {
marker.set("url", result.url);
}
if (marker.get("url")) {
html = "<a href='" + marker.get("url") + "' target=_blank>" + html + "</a>";
}
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

have a Google Map V3, can't update map.setCenter from user input

I'm new at this, but I have a Google V3 map that loads from the user's W3C browser geocode info, and I pull country, state, and city from the geocode object and update input boxes. If the user enters a street address, I want to geocode it via Google and change map.setCenter and setZoom, and display the updated map. When that works, I want to add a marker and infowindow. Despite hours of research and trials, I can't get the geocode and update to work. The Developer Tool in Chrome seems to indicate that execution ceases/fails at the geocoder.geocode line that is indicated in bold below. Here's relevant code.
var map, geocoder, marker, infowindow; //global variables
function initializeMap() {
// Try W3C Geolocation to geolocate desktop user
//initialize Google map, geolocate desktop user, and display after page loads
//find country, state, and city for the user's location - this all works
}
window.onload = initializeMap;
//change the Google Map after a user enters a street address
$("#streetAddress").blur(function() {
//if state, city and street address locations are present
if ( $(this).val().length > 0 && $("#state").val().length > 0 && $("#city3").val().length > 0 ) {
var gAddress = [$(this).val() + ", " + $("#city3").val() + ", " + $("#state").val()] ;
//get coordinates of this address
//if no geocode object exists, create one
if (!geocoder) {
geocoder = new google.maps.Geocoder(); //create Geocoder object else use existing one from initializeMap() ?
}
//create a GeocoderRequest object with user's street address
var geoCoderRequest = {address: gAddress}
//make a Geocoder request
geocoder.geocode( geoCoderRequest, function(results, status) { **//this line fails**
//check if status is OK
if ( status === google.maps.GeocoderStatus.OK) {
//update center of existing map on location returned for this address
map.setCenter(results[0].geometry.location);
map.setZoom(14);
}
});
} else {
return; //no action if gAddress is incomplete
}
});
According to the documentation, address should be a string, but you've created gAddress as an array.
Try:
var gAddress = $(this).val() + ", " + $("#city3").val() + ", " + $("#state").val();
Update: in response to your wanting to make the zoom happen after the map has initially loaded (e.g in response to user input), here's a simple example.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var start = 1;
function initialize() {
var homeLatlng = new google.maps.LatLng(51.476706,0); // London
var myOptions = {
zoom: 15,
center: homeLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function setZoom() {
map.setZoom(18);
}
function setTimedZoom() {
map.setZoom(start);
start = start+1;
if (start > 18) {
start = 1; // lets go round again and again; in reality you'd probably stop zooming at this point.
}
setTimeout(setTimedZoom, 3000);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
Zoom In
Timed
<div id="map_canvas"></div>
</body>
</html>