Custom Search box for Google map - html

I am developing web application using Google map JavaScript version. I need to add search box like Google Search box which is on Google map (like attached image). And I need to search custom places which are on my database.
If it is possible, how to do this?

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 initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
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.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Related

Map Center and Marker create based on text input

I want to define the map center and marker based on the text input HTML
It is work when i put lat/long on input text, but i need to press enter to make it work, i expected it will work when the map load without press enter,
<a id="myloc" type="text">-7.3344454, 112.7898796</a>
<button onclick="w3Load()">Load The Map</button>
<div id="map"></div>
The Java script :
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var input23 = new google.maps.LatLng(input11);
//var input23 = new google.maps.LatLng(document.getElementById("pac-input").value;
var map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: -33.8688, lng: 151.2195},
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('myloc');
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);
});
}
function mapLoad(){
document.getElementById("map").style.display = 'block';
google.maps.event.trigger(map, 'resize');
}
i expected it will work when the map load without press enter, because the lat long is generated automatically based on another input form
I get a javascript error with the code in your question: InvalidValueError: setCenter: not a LatLng or LatLngLiteral with finite coordinates: in property lat: NaN is not an accepted value. because input11 is null.
I believe what you want to do is:
make your element with id="myloc" an HTML <input> element (text) and set its value to your comma separated string of latitude,longitude coordinates.
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
parse the .value of that element to separate out the two numbers (the google.maps.LatLng object takes two numbers as arguments, not a comma separated string):
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
use the resulting google.maps.LatLng to initialize the center of your map and for the position of the marker:
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
})
Putting it all together:
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
proof of concept fiddle
code snippet:
function initAutocomplete() {
var input11 = document.getElementById("myloc").value
var coords = input11.split(",");
var input23 = new google.maps.LatLng(coords[0], coords[1]);
var map = new google.maps.Map(document.getElementById('map'), {
center: input23,
zoom: 13,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
})
// Create the search box and link it to the UI element.
var input = document.getElementById('myloc');
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);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<input id="myloc" type="text" value="-7.3344454, 112.7898796" />
<div id="map"></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=initAutocomplete" async defer></script>

I want to display the google map only after the search is clicked

I need to display the Google Map after I have performed my search, but the search box should have autocomplete locations/places. The search box should have the autocomplete places while searching and when clicked on THEN the map should be displayed with the location accordingly.
Here is the code:
<script>
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
&libraries=places&callback=initAutocomplete"
async defer></script>
And this is the other code:
<input id="pac-input" class="controls" type="text" placeholder="Search" >
<div id="map"></div>
One approach would be to set the visibility property of the <div id="map"></div> element to hidden in your CSS.
#map {
height: 100%;
visibility: hidden;
}
Then, at the end of your search box places_changed event handler, set the map element's visibility to visible:
document.getElementById('map').style.visibility = 'visible';
Also, in order to prevent the search box from going invisible as well, I would remove this line from your code:
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
Here is a JSBin with a working example.

info window not showing reverse geocoded address Google Maps V3

I'm coding a script that allows you to place a marker based on where you mouse click. I got that down. However, I cannot seem to get the infowindow to pop up when I pass in the reverse geocoded lat and lng. Could someone help me? Thanks!
Here is my code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
});
} // end of initalize.
/* place down marker based on where you click the mouse over a certain area on the map.
An infowindow should appear with the location of your marker.
*/
function placeMarker_and_attachMessage(position,map,num)
{
var event = google.maps.event.addListener;
var marker = new google.maps.Marker({
position: position,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: info_text(position)
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
// Takes in the position passed by the 'placeMarker_and_attachMessage' function and returns a human readable string
function info_text(position)
{
var location = position;
var latlngStr = location.split(',',2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat,lng);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
return results;
}
else
{
alert('could not pinpoint location');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
In the code you posted, count is not defined in
var marker = placeMarker_and_attachMessage(e.latLng,map,count);

Google Map API: Searching through text in infowindow possible?

I'm currently working on an application where various markers are placed with infowindows on a Google Map based on a user's posts. I've also included geocoding so that the user can change their location and view markers/posts in any area.
What I'd like to do is for the user to search through the text info in the infowindows via a form and the map then responds by showing the markers that contain that text window. I've searched through the API and I don't see this ability mentioned, although it seems like it should be achievable.
Any insight or information on how to accomplish this would be much appreciated.
Here's the current code within the application:
function mainGeo()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition( mainMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
}
else
{
alert("Sorry, but it looks like your browser does not support geolocation.");
}
}
var stories = {{storyJson|safe}};
var geocoder;
var map;
function loadMarkers(stories){
for (i=0;i<stories.length;i++) {
var story = stories[i];
(function(story) {
var pinColor = "69f2ff";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=S|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var point = new google.maps.LatLng(story.latitude, story.longitude);
var marker = new google.maps.Marker({position: point, map: map, icon: pinImage});
var infowindow = new google.maps.InfoWindow({
content: '<div >'+
'<div >'+
'</div>'+
'<h2 class="firstHeading">'+story.headline+'</h2>'+
'<div>'+
'<p>'+story.author+'</p>'+
'<p>'+story.city+'</p>'+
'<p>'+story.topic+'</p>'+
'<p>'+story.date+'</p>'+
'<p>'+story.copy+'</p>'+
'<p><a href='+story.url+'>Click to read story</a></p>'+
'</div>'+
'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,this);
});
})(story);
}
}
function mainMap(position)
{
geocoder = new google.maps.Geocoder();
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions =
{
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
loadMarkers(stories);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function error() {
alert("You have refused to display your location. You will not be able to submit stories.");
}
mainGeo();
Create three empty arrays (e.g., markers, infowindows, and matches)
As you instantiate the marker, reference the marker via an index in the markers array (e.g., markers[i] = marker)
As you instantiate the infowindow, reference it's content via an index in the infowindows array (e.g., infowindows[i] = htmltext [or whatever variable name you store your content in)
Search for the string in the infowindows array, store the indexes of the items that contain the string in the matches array, and then use a for loop with the matches array to add the markers from the markers array (based on the index values of the matches array).

Use iPhone location to update google map

I am building a cycle information site and want to be able to grab the users location from their iPhone so i update my Google map and provide the user with relevant information. There is a Drupal module called Geolocation which uses the HTML5 option to do this and i have found the code which it is performing the task in the module below.
// START: Autodetect clientlocation.
// First use browser geolocation
if (navigator.geolocation) {
browserSupportFlag = true;
$('#geolocation-help-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').append(Drupal.t(', or use your browser geolocation system by clicking this link') +': <span id="geolocation-client-location-' + i + '" class="geolocation-client-location">' + Drupal.t('My Location') + '</span>');
// Set current user location, if available
$('#geolocation-client-location-' + i + ':not(.geolocation-processed)').addClass('geolocation-processed').click(function() {
navigator.geolocation.getCurrentPosition(function(position) {
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Drupal.Geolocation.maps[i].setCenter(latLng);
Drupal.Geolocation.setMapMarker(latLng, i);
Drupal.Geolocation.codeLatLng(latLng, i, 'geocoder');
}, function() {
Drupal.Geolocation.handleNoGeolocation(browserSupportFlag, i);
});
});
}
Does anybody have any Google Maps API V3 experience of implementing this or similar? I would prefer the user to have to click "My Location" or equivalent to then use their iPhone's location to update the map rather than request it automatically. This is my Map and the array of markers that i have on it. How can i utilise the iPhones location to update it?
function initialize() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(51.51251523, -0.133201961),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
setMarkers(map, spots);
}
var spots = [
['Marylebone', 51.51811784, -0.144228881, '2.png', 2901, 'Broadcasting House - Marylebone</br>Available Bikes: 1</br>Number of Docks: 13</br> View more information about this dock'],
['Fitzrovia', 51.51991453, -0.136039674, '3.png', 2908, 'Scala Street - Fitzrovia</br>Available Bikes: 8</br>Number of Docks: 21</br> View more information about this dock'],
['Fitzrovia', 51.52351808, -0.143613641, '3.png', 2923, 'Bolsover Street - Fitzrovia</br>Available Bikes: 6</br>Number of Docks: 19</br> View more information about this dock'],
['Fitzrovia', 51.52025302, -0.141327271, '3.png', 2975, 'Great Titchfield Street - Fitzrovia</br>Available Bikes: 5</br>Number of Docks: 19</br> View more information about this dock'],
['Bloomsbury', 51.51858757, -0.132053392, '3.png', 2982, 'Bayley Street - Bloomsbury</br>Available Bikes: 12</br>Number of Docks: 25</br> View more information about this dock']
];
function setMarkers(map, locations) {
var image1 = new google.maps.MarkerImage('amber-spot.png',
new google.maps.Size(30, 36),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var spot = locations[i];
var myLatLng = new google.maps.LatLng(spot[1], spot[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: spot[3],
title: spot[0],
zIndex: spot[4],
html: spot[5]
});
bounds.extend(myLatLng);
map.fitBounds(bounds);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.html);
infowindow.open(map,this);
});
}
}
thanks
Lee
First you will need a javascript function that will be fired from a button press, or a link click. This function will use the geolocation api available through html5 to check if the user can provide you with their location and grab it if so. The remainder of the function will use the google maps api to pan to that lat lng coordinate and set the zoom level appropriately.
Here is the google maps api map object which has the methods you need:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
And this site has a great overview of basically everything you are trying to do:
http://www.html5laboratory.com/geolocation.php
Finally don't forget to save the location in your database or client side javascript array. If you are saving the data, warn the user of that for privacy implications.