How to Change Radius of google places service dynamically? - javascript

In the variable request i want to change the radius dynamically i.e when i enter an value such as 1000 in the text field parking areas within an radius of 1000 m should be visble like wise if i enter someother value it should change dynamiclly .
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=true&libraries=places"> </script>
<script>
var marker;
var map;
var infowindow = new google.maps.InfoWindow();
var myCenter;
var markers = [];
function initialize()
{
myCenter = new google.maps.LatLng(13.052413899999994,80.25065293862303);
map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myCenter,
zoom: 15
});
}
function some()
{
var request = {
location: myCenter,
radius: 500,
types: ['bank']
};
var 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 < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place)
{
var placeLoc = place.geometry.location;
marker = new google.maps.Marker({
position: place.geometry.location
});
marker.setIcon({
url:'bank.png',
size: new google.maps.Size(70, 71),
anchor: new google.maps.Point(17, 14),
scaledSize: new google.maps.Size(35, 35)
});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
markers.push(marker);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 50%; float:left"></div>
<div style="width:46%; float:left">
<input type="number" id="inputarea">
<button onclick="some();">Banks</button>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>

Like this:
function some()
{
var request = {
location: myCenter,
radius: parseInt(document.getElementById('inputarea').value, 10),
types: ['bank']
};
...
}

Related

I'm trying to make a restaurant locator app and can't get the markers to appear

I'm trying to get markers for restaurants to drop on my map and it's not working. Any help would be appreciated. Do I need to add a query method? I am trying not too as I'm going to let the location be static when finished. Here is my relevant code,
<script>
var map;
function initialize() {
var center = new google.maps.LatLng(37.422, -122.084058);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 13
});
var request = {
location: center,
radius: 8047,
types: ['restaurant']
};
var service = new google.places.PlaceService(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
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
PlacesService needs an API_KEY.
var map;
var infowindow;
function initMap() {
var center = new google.maps.LatLng(37.422, -122.084058);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 13
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: center,
radius: 8047,
type: ['restaurant']
}, 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
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script>
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB1tbIAqN0XqcgTR1-FxYoVTVq6Is6lD98&libraries=places&callback=initMap" async defer></script>
</body>
</html>

trouble getting my mouseover on markers to work

I have created my code below with the mouseover affect at the end, but it does not work. Have I put it in the wrong place? I just can't seem to get it to work. Eventually I would like to get a certain type of info displayed on them but each step at a time, trying to get the basic to work first.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(address){
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);
}
});
}
});
}
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="top: 0; right: 0; width:380px; height: 500px; float:right;padding-left:10px; padding-right:10px;">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right"></div>
You need to:
define contentString
associate the marker with the infowindow content. One way of doing that is with anonymous function closure as in this related question Google Maps JS API v3 - Simple Multiple Marker Example, or with an explicit createMarker function as in my example below.
Note: This approach will only work for approximately 10 addresses, after which it will run into the Geocoder rate limits.
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
proof of concept fiddle
code snippet:
var markers = [];
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
google.maps.event.addDomListener(window, "load", up206b.initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="New York, NY" />
<input id="address2" value="Newark, NJ" />
<input type="button" value="Submit" onClick="up206b.geocode()">
<div id="map_canvas"></div>

Loading Google maps marker on button click using geolocation

My code should define the geolocation of the user and assign it the value pos. I then want to use this value of pos to create a marker upon a button click.
However, I do not get a point being plotted. Both position and map are global variables that have already been assigned, so can't figure out why I am not getting a response.
Any help would be much appreciated!
Javascript:
var map;
var service;
var marker;
var pos;
var infowindow;
var marker2;
function initialize() {
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
panControl: true,
streetViewControl: true,
mapTypeControl: true,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here'
});
var request = {
location: pos,
radius: 1000,
types: ['doctor']
};
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
},
function () {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if(errorflag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(51.5334410,-0.1396180),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
pos = options.position;
var request = {
location: pos,
radius: 1000,
types: ['hospital']
};
infowindow = new google.maps.InfoWindow();
var 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
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.vicinity);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
document.getElementById("button").addEventListener("click", function(){
marker2 = new google.maps.Marker({
position : pos,
map: map
})
});
HTML:
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<meta name="keywords" content="TBC" />
<meta name="description" content="TBC" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name=viewport content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/main.css">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script src="assets/js/jquery-2.1.1.min.js"></script>
<script src="assets/js/main.js"></script>
</head>
<body>
<div id="header">
<img src="https://www.bhf.org.uk/~/media/images/admin/logo/bhf-logo.png" width="40" />
<h1><strong>British Heart Foundation:</strong>
<br />Defibrillator Locator</h1>
<div class="clearfix"> </div>
</div>
<div id="map-canvas"></div>
<div id="firstResult" class="results"> <button id="button"> Register </button> </div>
<div class="results"> Test </div>
<div class="results"><a class="address" href= "C:\Users\jacholt\Documents\Analytics\BHF - 11.05- Page 2\index.html"> Report a Defibrillator </a> </div>
<div class="instruct"> <a class="address" href="https://www.bhf.org.uk/heart-health/nation-of-lifesavers/using-defibrillators"> How to use a defibrillator</a> </div>
</body>
</html>
Add your "click" listener function inside the initialize function. That runs when the onload event fires and the DOM has been rendered. Before that the button can't be found in the DOM.
code snippet:
var map;
var service;
var marker;
var pos;
var infowindow;
var marker2;
function initialize() {
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
panControl: true,
streetViewControl: true,
mapTypeControl: true,
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'You Are Here'
});
var request = {
location: pos,
radius: 1000,
types: ['doctor']
};
map.setCenter(pos);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
},
function () {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if(errorflag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(51.5334410,-0.1396180),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
pos = options.position;
var request = {
location: pos,
radius: 1000,
types: ['hospital']
};
infowindow = new google.maps.InfoWindow();
var 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
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.vicinity);
infowindow.open(map, this);
});
}
document.getElementById("button").addEventListener("click", function(){
marker2 = new google.maps.Marker({
position : pos,
map: map
})
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<div id="header">
<img src="https://www.bhf.org.uk/~/media/images/admin/logo/bhf-logo.png" width="40" />
<h1><strong>British Heart Foundation:</strong>
<br />Defibrillator Locator</h1>
<div class="clearfix"> </div>
</div>
<div id="map-canvas"></div>
<div id="firstResult" class="results"> <button id="button"> Register </button> </div>
<div class="results"> Test </div>
<div class="results"><a class="address" href= "C:\Users\jacholt\Documents\Analytics\BHF - 11.05- Page 2\index.html"> Report a Defibrillator </a> </div>
<div class="instruct"> <a class="address" href="https://www.bhf.org.uk/heart-health/nation-of-lifesavers/using-defibrillators"> How to use a defibrillator</a> </div>

Markers not created after passing JSON

Edit after help from Roberto:
Python newbie. The app uses Maps Javascript API v3 on the front end. Backend is webapp2/GAE. I'm assuming I'm not doing the json properly either. Markers not created properly after passing the JSON.
q = Building.query()
buildings = q.fetch()
some_json = []
for building in buildings:
some_json.append(OrderedDict([('lat', float(building.lat)), ('lng', float(building.lng)), ('content', building.uuid)]))
appended_json = json.dumps(some_json)
HTML:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body, #map-canvas { height: 100%; margin: 0; padding: 0;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMfzvCXM-LUe43cZ0mB2iDxx4aNOySkrQ">
</script>
<script type="text/javascript">
function initialize() {
var input_value = document.getElementById("lat").value;
var converted_value = JSON.stringify(input_value);
console.log(input_value);
var json = JSON.parse(converted_value);
console.log(json);
var locations = json;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][2]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<input id="lat" hidden="hidden" value="{{ appended_json }}">
</body>
</html>
Console outputs the following, if the output is proper and raises no errors:
[{"lat": 39.2831792, "lng": -80.56741099999999, "content": "782f7100c13511e49f92ab5e18d4b38e"}] viewbuildings:17
[{"lat": 39.2831792, "lng": -80.56741099999999, "content": "782f7100c13511e49f92ab5e18d4b38e"}]
Even if the output is not proper, it still not raises anything.
Edit:
Exact HTML browser sees is the following
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body, #map-canvas { height: 100%; margin: 0; padding: 0;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMfzvCXM-LUe43cZ0mB2iDxx4aNOySkrQ">
</script>
<script type="text/javascript">
function initialize() {
var input_value = document.getElementById("lat").value;
var converted_value = JSON.stringify(input_value);
console.log(input_value);
var json = JSON.parse(converted_value);
console.log(json);
var locations = json;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][2]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<input id="lat" hidden="hidden" value="[{"lat": 39.2831792, "lng": -80.56741099999999, "content": "782f7100c13511e49f92ab5e18d4b38e"}]">
</body>
</html>
Your code is expecting your JSON to look like this:
[[39.2831792,-80.56741099999999,"782f7100c13511e49f92ab5e18d4b38e"]]
Your JSON doesn't look like that, it looks like:
[{"lat": 39.2831792,"lng": -80.56741099999999,"content": "782f7100c13511e49f92ab5e18d4b38e"}];
Change the code to process your JSON format:
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].content);
infowindow.open(map, marker);
}
})(marker, i));
}
You are also using JSON.stringify and JSON.parse incorrectly. The content of your input element is a JSON string, you only need to pass it to JSON.parse to get a JSON object out of it:
working code snippet:
function initialize() {
var input_value = document.getElementById("lat").value;
var json = JSON.parse(input_value);
var locations = json;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
map: map
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i].content);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="map-canvas"></div>
<input id="lat" hidden="hidden" value="[{"lat": 39.2831792, "lng": -80.56741099999999, "content": "782f7100c13511e49f92ab5e18d4b38e"}]">

PHP google map get Latitude and Longitude by type

Hi guys anybody know how to get latitude and longitude by type on google map using PHP or Javascript?
for example, I want to get all restaurant on this location:
location: United Kingdom, devon
type:restaurant
it should return name of restaurant, latitude, longitude.
any help would be appreciated :)
Check this
$(function () {
var lat = 44.88623409320778,
lng = -87.86480712897173,
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
//zoomControl: true,
//zoomControlOptions: google.maps.ZoomControlStyle.LARGE,
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function (event) {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
$('.MapLat').val(place.geometry.location.lat());
$('.MapLon').val(place.geometry.location.lng());
});
google.maps.event.addListener(map, 'click', function (event) {
$('.MapLat').val(event.latLng.lat());
$('.MapLon').val(event.latLng.lng());
infowindow.close();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"latLng":event.latLng
}, function (results, status) {
console.log(results, status);
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("#searchTextField").val(results[0].formatted_address);
}
});
});
function moveMarker(placeName, latlng) {
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
//infowindow.open(map, marker);
}
});
Working demo fiddle
HTML AND JS
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link href="default.css"
rel="stylesheet">
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
function initialize() {
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);
var input = /** #type {HTMLInputElement} */(document.getElementById('target'));
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
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)
};
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);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<div id="panel">
<input id="target" type="text" placeholder="Search Box">
</div>
<div id="map-canvas"></div>
</body>
</html>
AND CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
#media print {
html, body {
height: auto;
}
#map-canvas, #map_canvas {
height: 650px;
}
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
REFER HERE FOR MORE ! GOOGLE PLACES

Categories

Resources