Embed Google Map with search bar - google-maps

I'd like to create a Google map with a search box to embed into my site. I've already created the custom map with my markers via my google maps account.
Unfortunately the html embedded maps don't include a search box within a map, so I believe I need the Google API. All I need a map with a search box and zoom (zoom seems there by default), so that I can add places of interest (clubs in my case) from my Google account. I would like visitors to be able to type a place of interest in the search box, and it will take them to that location on the map, and show local clubs nearby.
I've already spent some time looking for examples, so that I can modify it to suit my needs, but have not found something similar. My programming skills are quite limited, so I'm looking for a simple solution.
Can anyone point me in the right direction here please?

Use the Places Autocomplete along with custom controls.

This might help another users for head start.
I have written a script that has two search boxes with Google place search auto completion and then It calculates the route and shows on the map.
Below is example link. (just download it and open in browser)
Google Place Search & Calculate route between two locations

You may add a text box to your page and get content from the text box. This is independent from Google map.

See the JSFiddle attached here: Embedded Google Map With Search Bar from Google Developers.
The below snippet DOES NOT work because it needs your Google API
Key.
// 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() {
const 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.
const input = document.getElementById("pac-input");
const 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", () => {
searchBox.setBounds(map.getBounds());
});
let markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(marker => {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
const bounds = new google.maps.LatLngBounds();
places.forEach(place => {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
const 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,
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);
});
}
/* 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;
}
<!DOCTYPE html>
<html>
<head>
<title>Places Search Box</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly"
defer
></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script src="./app.js"></script>
</head>
<body>
<input
id="pac-input"
class="controls"
type="text"
placeholder="Search Box"
/>
<div id="map"></div>
</body>
</html>

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>

google maps API geocoding get address components [duplicate]

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>

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.

Google maps search API

Can someone tell me if is possible in google maps search api, when you search city name in your own language, to return the city name always in english?
So lets say you type city name in russian, but you want to return city name in english language
If I understand your use case correctly, I think this is doable using a workaround. For example, you are searching for "St. Petersburg" (a city in Russia). The Russian name of that city would be "Санкт-Петербург" as per Google Translate.
Using Google Maps Javascript API Places search box, you can log the value of variable places. With this, you can now see the returned results once the event "places_changed" has been fired.
Here's a sample result:
"result" : {
"address_components" : [
{
"long_name" : "Saint Petersburg",
"short_name" : "Saint Petersburg",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Saint Petersburg",
"short_name" : "Saint Petersburg",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Russia",
"short_name" : "RU",
"types" : [ "country", "political" ]
}
],
"adr_address" : "\u003cspan class=\"region\"\u003eSaint Petersburg\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eRussia\u003c/span\u003e",
"formatted_address" : "Saint Petersburg, Russia"
...
}
You will notice these properties: "address_components" and "formatted_address" has address that is in english language.
If you are concerned about the address in your searchbox not in english language, you can change it by parsing the address_components key/values or by formatted_address and then setting it as value of the searchbox.
Sample implementation:
document.getElementById('pac-input').value = places[0].formatted_address;
Working demo below:
// 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();
console.log(places);
if (places.length == 0) {
return;
}
document.getElementById('pac-input').value = places[0].formatted_address;
// 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);
});
}
#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;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&libraries=places&language=en&callback=initAutocomplete"
async defer></script>
And that's it. Happy coding and goodluck on your project.

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>