google maps API geocoding get address components [duplicate] - google-maps

This question already has an answer here:
How to get country from google maps api?
(1 answer)
Closed 4 years ago.
I'm working with google map API(geocoding) and I noticed the following. If I print the array for "x" address, it prints an array of objects of size 9. where the country is in the index 6. If I enter some other "y" address, sometimes the array of objects is less than 9 and the index to get the country is not 6 anymore. I have tried with different addresses as some of them have the size consistent as 9 some of them at 6 some of them 7 and so on. Is there a set way for me to access the country without having to check the size of the array and avoid this issue?
my code
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
this.addressArray = place.address_components;
if(this.addressArray.length === 9) {
this.country = this.addressArray[6].short_name;
this.zipcode = this.addressArray[7].short_name;
} else {
this.country = this.addressArray[5].short_name;
this.zipcode = this.addressArray[6].short_name;
}
I figured I can use place.formatted_address and access the last word which is always the country, but for zipcode and some other information on the address the order is not always the same.
Below is an example of the structure of the array of objects I'm printing.
I thought about filtering the array to find the index of types that contains the word country,zipcode, etc and based on the index returned get the country or whatever I want to retrieve. I wonder if there's an easier way to accomplish this straight from the google API geocode.
This question How to get country from google maps api? talks about someone entering the address. My application uses google autocomplete. I thought the API was smarter to handle the missing data of people not entering a complete address. Also, the answer address in that question is part of my explanation of my question of me saying I knew I could filter the array

related question: Wrong country code returned by Google Geocoder
You need to parse through the address_components array's types, looking for the entry with a type of country.
var country = '';
for (var i = 0; i < place.address_components.length; i++) {
for (var j = 0; j < place.address_components[i].types.length; j++) {
if (place.address_components[i].types[j] == "country") {
country = place.address_components[i];
}
}
}
document.getElementById("country").innerHTML = country.long_name +" (" + country.short_name +")";
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
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.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var country = '';
for (var i = 0; i < place.address_components.length; i++) {
for (var j = 0; j < place.address_components[i].types.length; j++) {
if (place.address_components[i].types[j] == "country") {
country = place.address_components[i];
}
}
}
document.getElementById("country").innerHTML = country.long_name + " (" + country.short_name + ")";
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = country.long_name;
infowindow.open(map, marker);
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 30px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
<div class="pac-card" id="pac-card">
<div>
<div id="type-selector" class="pac-controls">
</div>
<div id="pac-container">
<input id="pac-input" type="text" placeholder="Enter a location">
</div>
</div>
</div>
<div id="country"></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>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>

Related

How to get parameters like country,city,state and area information when user share their location...?

I am providing a form to a user which takes some information about the user.
Instead of taking the address by providing them options like drop box which includes many countries,cities,states and area, I would provide them Google Map so that user can share their location and when user submit the form, then I must be able to get country,city,state,area and latitude and longitude and store that in MySQL database
When a user share their location, below codes gives all the required data, like country,state,city,area,pin-code, latitude,longitude and many more....
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Search Box</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// 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 initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var 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(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html>

How to display additional information in Google Maps autocomplete suggestions?

I am using Google Places autocomplete to select cities by name. Currently it displays only the city name and the country it belongs to, in the suggestions drop down.
I have checked and found that the "address_components" object, that gets populated when a city is selected, has additional attibutes like state/province and other parts of the address. So, it is clear that the Google's API provide additional information other than merely the city and country names.
What I am trying to achieve is, displaying a couple of those additional data in the suggestions dropdown.
Is there a way to do that?
(I have marked on the screenshot where I need to display the additional attributes)
Here is the code.
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete&query=locality" async defer></script>
<script>
var searchBox;
function initAutocomplete() {
var options = {types: ['(cities)']};
var input = document.getElementById('placeAuto');
searchBox = new google.maps.places.Autocomplete(input);
searchBox.addListener('place_changed', fillInAddress);
}
function fillInAddress()
{
var place = searchBox.getPlace();
console.log(place);
}
</script>
As I commented already, you can do that by using the Autocomplete and Places services and the getPlacePredictions method, but I would not recommend this approach as it will make a high number of requests to the API (one for each result, each time a user types something in the address field).
View the snippet in full screen mode as it won't fit hereunder or check it on JSFiddle.
In this example I have added the place latitude and longitude in the autocomplete results.
var autocompleteService, placesService, results, map;
function initialize() {
results = document.getElementById('results');
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(50, 50)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Bind listener for address search
google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
});
// Show results when address field is focused (if not empty)
google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {
if (document.getElementById('address').value !== '') {
results.style.display = 'block';
getPlacePredictions(document.getElementById('address').value);
}
});
// Hide results when click occurs out of the results and inputs
google.maps.event.addDomListener(document, 'click', function(e) {
if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {
results.style.display = 'none';
}
});
autocompleteService = new google.maps.places.AutocompleteService();
placesService = new google.maps.places.PlacesService(map);
}
// Get place predictions
function getPlacePredictions(search) {
autocompleteService.getPlacePredictions({
input: search,
types: ['geocode']
}, callback);
}
// Place search callback
function callback(predictions, status) {
// Empty results container
results.innerHTML = '';
// Place service status error
if (status != google.maps.places.PlacesServiceStatus.OK) {
results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
return;
}
// Build output for each prediction
for (var i = 0, prediction; prediction = predictions[i]; i++) {
// Get place details to inject more details in autocomplete results
placesService.getDetails({
placeId: prediction.place_id
}, function(place, serviceStatus) {
if (serviceStatus === google.maps.places.PlacesServiceStatus.OK) {
// Create a new result element
var div = document.createElement('div');
// Insert inner HTML
div.innerHTML += '<span class="pac-icon pac-icon-marker"></span>' + place.adr_address + '<div class="pac-item-details">Lat: ' + place.geometry.location.lat().toFixed(3) + ', Lng: ' + place.geometry.location.lng().toFixed(3) + '</div>';
div.className = 'pac-item';
// Bind a click event
div.onclick = function() {
var center = place.geometry.location;
var marker = new google.maps.Marker({
position: center,
map: map
});
map.setCenter(center);
}
// Append new element to results
results.appendChild(div);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
body,
html {
font-family: Arial, sans-serif;
padding: 0;
margin: 0;
height: 100%;
}
#map-canvas {
height: 150px;
margin-bottom: 5px;
}
table {
border-collapse: collapse;
margin-left: 20px;
}
table td {
padding: 3px 5px;
}
label {
display: inline-block;
width: 160px;
font-size: 11px;
color: #777;
}
input {
border: 1px solid #ccc;
width: 170px;
padding: 3px 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}
.pac-container {
background-color: #fff;
z-index: 1000;
border-radius: 2px;
font-size: 11px;
box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
width: 350px;
}
.pac-icon {
width: 15px;
height: 20px;
margin-right: 7px;
margin-top: 6px;
display: inline-block;
vertical-align: top;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
background-size: 34px;
}
.pac-icon-marker {
background-position: -1px -161px;
}
.pac-item {
cursor: pointer;
padding: 0 4px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
line-height: 30px;
vertical-align: middle;
text-align: left;
border-top: 1px solid #e6e6e6;
color: #999;
}
.pac-item:hover {
background-color: #efefef;
}
.pac-item-details {
color: lightblue;
padding-left: 22px;
}
.pac-item-error,
.pac-item-error:hover {
color: #aaa;
padding: 0 5px;
cursor: default;
background-color: #fff;
}
<div id="map-canvas"></div>
<table>
<tr>
<td>
<label for="address">Address:</label>
</td>
</tr>
<tr>
<td>
<input id="address" placeholder="Enter address" type="text" tabindex="1" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="results" class="pac-container"></div>
</td>
</tr>
</table>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

How to identify multiple names used in google maps to key to the same name?

Typically, a place name (e.g. Mumbai) has different names that show up in Google maps - e.g. Mumbai Maharashtra, Mumbai India or just Mumbai.
how do we identify it's the same place (without depending on co-ordinates which are known to change)? Something like a unique key or string name that I can use to look up into my application?
This key exists. It is name the Place IDs. A place Id is unique for each address in the world. You can convert an address to a place id with this function:
var request = {
location: map.getCenter(),
radius: '500',
query: 'Google Sydney'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log (results[0].place_id);
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[0].place_id,
location: results[0].geometry.location
}
});
}
}
This is an other example maybe a quite more complicated:
// This sample uses the Place Autocomplete widget to allow the user to search
// for and select a place. The sample then displays an info window containing
// the place ID and other information about the place that the user has
// selected.
// 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('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
// Set the position of the marker using the place ID and location.
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location
});
marker.setVisible(true);
document.getElementById('place-name').textContent = place.name;
document.getElementById('place-id').textContent = place.place_id;
document.getElementById('place-address').textContent =
place.formatted_address;
infowindow.setContent(document.getElementById('infowindow-content'));
infowindow.open(map, marker);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 17px;
margin-top: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
.controls:focus {
border-color: #4d90fe;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"
async defer></script>
This is another example of reverse geocoding with place id:
// Initialize the map.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.72, lng: -73.96}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
geocodePlaceId(geocoder, map, infowindow);
});
}
// This function is called when the user clicks the UI button requesting
// a reverse geocode.
function geocodePlaceId(geocoder, map, infowindow) {
var placeId = document.getElementById('place-id').value;
geocoder.geocode({'placeId': placeId}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#floating-panel {
width: 440px;
}
#place-id {
width: 250px;
}
<div id="floating-panel">
<!-- Supply a default place ID for a place in Brooklyn, New York. -->
<input id="place-id" type="text" value="ChIJd8BlQ2BZwokRAFUEcm_qrcA">
<input id="submit" type="button" value="Reverse Geocode by Place ID">
</div>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
All this is a bit complicated...
You can consult the google developer web site for more informations:
Geocoding place id
Example geocoding
Reverse geocoding
Example reverse geocoding
Tell me if you do not understand or if you have some questions or some comments.

How can I add info window in places searchbox

I want to add info window to this example 'Places search box' https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
and info window should be like this example which contains name with google link, address, telephone, rating and website https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-hotelsearch
Typically StackOverflow is not used to ask somebody to write code for you. You just need to combine these two examples to get the desired behavior.
That being said, below you can find the merged example, that introduces info windows from the second example to the first example.
var map, places, infoWindow;
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById('info-content')
});
places = new google.maps.places.PlacesService(map);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
google.maps.event.clearListeners(marker, 'click');
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
var count = 0;
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var 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(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
markers[count].placeResult = place;
google.maps.event.addListener(markers[count], 'click', showInfoWindow);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
count++;
});
map.fitBounds(bounds);
});
}
function showInfoWindow() {
var marker = this;
places.getDetails({placeId: marker.placeResult.place_id},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
}
function buildIWContent(place) {
document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' +
'src="' + place.icon + '"/>';
document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url +
'">' + place.name + '</a></b>';
document.getElementById('iw-address').textContent = place.vicinity;
if (place.formatted_phone_number) {
document.getElementById('iw-phone-row').style.display = '';
document.getElementById('iw-phone').textContent =
place.formatted_phone_number;
} else {
document.getElementById('iw-phone-row').style.display = 'none';
}
// Assign a five-star rating to the hotel, using a black star ('✭')
// to indicate the rating the hotel has earned, and a white star ('✩')
// for the rating points not achieved.
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
document.getElementById('iw-rating-row').style.display = '';
document.getElementById('iw-rating').innerHTML = ratingHtml;
}
} else {
document.getElementById('iw-rating-row').style.display = 'none';
}
// The regexp isolates the first part of the URL (domain plus subdomain)
// to give a short URL for displaying in the info window.
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website === null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
document.getElementById('iw-website-row').style.display = '';
document.getElementById('iw-website').textContent = website;
} else {
document.getElementById('iw-website-row').style.display = 'none';
}
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
.placeIcon {
width: 20px;
height: 34px;
margin: 4px;
}
.hotelIcon {
width: 24px;
height: 24px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<div style="display: none">
<div id="info-content">
<table>
<tr id="iw-url-row" class="iw_table_row">
<td id="iw-icon" class="iw_table_icon"></td>
<td id="iw-url"></td>
</tr>
<tr id="iw-address-row" class="iw_table_row">
<td class="iw_attribute_name">Address:</td>
<td id="iw-address"></td>
</tr>
<tr id="iw-phone-row" class="iw_table_row">
<td class="iw_attribute_name">Telephone:</td>
<td id="iw-phone"></td>
</tr>
<tr id="iw-rating-row" class="iw_table_row">
<td class="iw_attribute_name">Rating:</td>
<td id="iw-rating"></td>
</tr>
<tr id="iw-website-row" class="iw_table_row">
<td class="iw_attribute_name">Website:</td>
<td id="iw-website"></td>
</tr>
</table>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initAutocomplete"
async defer></script>
You can find this example on jsbin as well: http://jsbin.com/xipagud/edit?html,output
Hope this helps!

Embed google map using share url

Say, you go to google maps and search for 'Walmart', then choose the first Walmart in the list, and you get a URL like:
https://www.google.com/maps/place/Walmart+Supercenter/#41.7991677,-70.5882922,10z/data=!4m5!1m2!2m1!1swalmart!3m1!1s0x89e4c6127cc5b685:0x104d337439f46ea9
then if you go to that URL, it gives you a valid map with the pinpoint. This (above) is the URL that would be stored in my database, thus the URL I want to use to embed a map.
Of course, I can't use that URL to embed in an iframe, and I instead have to use:
https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d380717.11119594605!2d-70.5882922!3d41.7991677!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x89e4c6127cc5b685%3A0x104d337439f46ea9!2sWalmart+Supercenter!5e0!3m2!1sen!2sus!4v1445294674664
So... for any shareable Google Maps url, how can I convert it to an embeddable url to be used as the iframe src?
I can do it server-side using PHP or client-side with javascript. use of regex would be acceptable.
This could do the trick :
$matches = [];
preg_match("/#(.*?),(.*?),/",$str,$matches);
$place = $matches[1];
preg_match("/#(.*?),(.*?),/",$str,$matches);
$lat = $matches[1];
$long = $matches[2];
echo '<iframe src="https://www.google.com/maps/embed/v1/place?q='.$place.'&center='.$lat.','.$long.'&key=AIzaSyAN0om9mFmy1QN6Wf54tXAowK4eT0ZUPrU&zoom=8" frameborder="0"></iframe>';
After the first # char it is located the latitude and logitude, which you can extract using the regex I wrote, and than capture the output on 2 groups and add it that on the embedd URL.
Don't know why you want to do this conversion and all , but if you are using javascript client side , then you can use Google maps v3 for javascript
Then you will directly get lat/lng and you can store them and use for all future calls, which seems much cleaner approach.
See the following code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places Searchbox</title>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
var marker;
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
console.log('place: '+places[0]);
if(marker!=null)
marker.setMap(null);
var icon = {
url: places[0].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(25, 25)
};
marker = new google.maps.Marker({
map: map,
// icon: icon,
title: places[0].name,
position: places[0].geometry.location
});
map.setCenter(places[0].geometry.location);
//save places[0].geometry.location for all future reference
});
// [END region_getplaces]
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>
</body>
</html>
of course if you need you can remove search list and by default always select 1st result.
Client side option:
$(function() {
var str = 'https://www.google.com/maps/place/Walmart+Supercenter/#41.7991677,-70.5882922,10z/data=!4m5!1m2!2m1!1swalmart!3m1!1s0x89e4c6127cc5b685:0x104d337439f46ea9';
var matches = str.match(/\/#([\d\.,-]+)z\//)[1];
var splits = matches.split(',');
var lat = splits[0];
var long = splits[1];
var zoom = splits[2];
var url = 'http://maps.google.com/maps?q=' + lat + ',' + long + '&z=' + zoom + '&output=embed';
$('#output').html('<iframe style = "width:200px;height:400px" src = ' + url + '></iframe>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output' style="width:200px;height:400px"></div>