Preview
So far I can click on the map and then the Longitude and Latitude will be shown on the text field below the map, on the next click the marker will move to the new location and the new Longitude and Latitude will be shown on the text field. But I'm trying to make the shown Longitude and Altitude to be saved once the "SAVE" button is clicked, so the marker will be there and not move on the next click.
Sorry for my horrible explanation skill guys,
TLDR: How can i store the current longitude and latitude without it disappearing on the next click ?
Here's my code to show the current longitude and latitude
function taruhMarker(petasaya, posisiTitik){
if( marker ){
marker.setPosition(posisiTitik);
}
else {
marker = new google.maps.Marker({
position: posisiTitik,
map: petasaya
});
}
document.getElementById("lat").value = posisiTitik.lat();
document.getElementById("lng").value = posisiTitik.lng();
document.getElementById("info").value = posisiTitik.info();
}
And here's the code i use for the text field and button
<tr>
<td><input type="text" id="lat" name="lat" value="" readonly> </td>
<td><input type="text" id="lng" name="lng" value="" readonly></td>
</tr>
<tr>
<td><h3> Info Marker </h3></td>
</tr>
</table>
<center><textarea rows="7" cols="50" ></textarea><br><br>
<center><input button type="button" id="button" value="SAVE"></input>
I live in Indonesia so most of the variables i use are in Indonesian languages
You can simply store multiple markers in an array in order to distinguish each, and display it's corresponding coordinates to your input texts without the use of "SAVE" button.
I tried to utilize and replicate the piece of code you've provided(including variables) and here's what i've came up:
It is important that you set global variable markers as an array: var markers = [];
function taruhMarker(posisiTitik) {
var marker = new google.maps.Marker({
position: posisiTitik,
map: map
});
markers.push(marker);
document.getElementById("lat").value = posisiTitik.lat();
document.getElementById("lng").value = posisiTitik.lng();
Working JSBin: http://jsbin.com/zayejuc
I've also added code snippet below:
var map;
var markers = [];
function initMap() {
var haightAshbury = {lat: -5.4031649, lng: 105.2635957};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: haightAshbury
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
taruhMarker(event.latLng);
});
}
// Adds a marker to the map and push to the array.
function taruhMarker(posisiTitik) {
var marker = new google.maps.Marker({
position: posisiTitik,
map: map
});
markers.push(marker);
document.getElementById("lat").value = posisiTitik.lat();
document.getElementById("lng").value = posisiTitik.lng();
marker.addListener('click', function() {
infowindow.open(map, marker);
});
//delete markers
var tst = 1;
var contentString = posisiTitik+'<br>'+'<input onclick="deleteMarkers('+markers.length+');" type=button value="Delete Marker">';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
}
function deleteMarkers(tst) {
markers[tst-1].setMap(null)
}
#map {
height: 100%;
}
#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;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
</head>
<body>
<div id="map"></div>
<div id="floating-panel">
<input id="lat" type="text" placeholder="Latitude">
<input id="lng" type="text" placeholder="Longitude">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0wB2s8fFD1L9BBEWRKidcH31nrBZ4r0c&callback=initMap">
</script>
</body>
</html>
Related
I'm trying to put markers coordinates into the input field but I don't know how to do it ;(
My example is here:
https://skni.org/map.html
I get coordinates in that variable:
var infowindow = new google.maps.InfoWindow({
content: '' + marker.getPosition() + ''
I would like to be able to put couple markers on the map and then all coordinates values should go into the input field so I can send them into the database
My code:
script.js
// In the following example, markers appear when the user clicks on the map.
// The markers are stored in an array.
// The user can then click an option to hide, show or delete the markers.
var map;
var markers = [];
window.initMap = function(){
var haightAshbury = {lat: 52.131514, lng: 20.913248};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: haightAshbury,
mapTypeId: 'satellite'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Set lat/lon values for this property',
draggable: true
});
var infowindow = new google.maps.InfoWindow({
content: '' + marker.getPosition() + ''
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
html code:
<!DOCTYPE html>
<html>
<head>
<title>Remove Markers</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;
}
#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;
}
</style>
</head>
<body>
<div id="floating-panel">
<form action="/action_page.php">
Coordinates:<br>
<input type="text" name="coordinates" size="55" value="How to get coordinates from info window after clicking on markers?">
<br>
<input type="submit" value="Submit">
</form>
<br />
<input onclick="clearMarkers();" type=button value="Hide Markers">
<input onclick="showMarkers();" type=button value="Show All Markers">
<input onclick="deleteMarkers();" type=button value="Delete Markers">
</div>
<div id="map"></div>
<p>Click on the map to add markers geocoorditanes.</p>
<div id="map-canvas"> </div>
<script src="script.js" ></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
append this to your addMarker() function:
var allCoordinates = [];
markers.forEach(function(marker){
allCoordinates.push(marker.getPosition().lat() + "," + marker.getPosition().lng());
})
$("input[name=coordinates]").val(allCoordinates);
Of course you should change the format of the coordinates as you need and this can probably be refactored to be more efficient.
I have so far created a template of what i want and have manged to start getting each area to work, still got some work to do but I am currently trying to embed a KML file as a layer for my google map.
Here is my full coding below.
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var markers = [];
function createMarker(latlng, html, map, refnum) {
var latlngtxt = (latlng.lat() + ',' + latlng.lng()).split(',');
$.each(latlngtxt, function(i, v){
v = Math.round(v);
v += v > 0? (i? 'E' : 'N') : (i? 'W' : 'S');
latlngtxt[i] = v.replace(/^-/, '');
});
latlngtxt = latlngtxt.join(', ');
var ref = $.trim($('#reference').val());
//ref = ref? ref + '<br>' : '';
var infowindow = new google.maps.InfoWindow({
content: ref || html //+ '#' + (markers.length + 1) + '<br>' + html + '<br>' + latlngtxt
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
html: html,
infowindow: infowindow
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
$('#supplementwindow').html(infowindow.content).fadeIn();
});
marker.addListener('mouseout', function() {
infowindow.close();
$('#supplementwindow').fadeOut();
});
markers.push(marker);
}
var up206b = {};
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 ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();
up206b.geocode = function() {
/* for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = []; */
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address, refnum) {
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, refnum);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
jQuery(function($){
$('#removemarker').click(function(){
var tm = $('#themarkers'), si = tm.get(0).options.selectedIndex, $o = $('option', tm).eq(si), i = $o.val();
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
v.setMap(null);
markers.splice(idx, 1);
return false;
}
});
$o.remove();
bounds = new google.maps.LatLngBounds();
if(markers.length){
$.each(markers, function(i, v){
bounds.extend(v.position);
});
map.fitBounds(bounds);
}
if(markers.length < 2){
map.setZoom(markers.length? 13 : 8);
}
});
$('#themarkers').change(function(){
this.title = this.options[this.options.selectedIndex].title;
var i = this.value;
if(!i){return;}
$.each(markers, function(idx, v){
if(v.html === i){
map.setCenter(v.position);
map.setZoom(10);
return false;
}
});
});
$('#showall').click(function(){
$('#themarkers').get(0).selectedIndex = 0;
if(!markers.length){
map.setCenter(new google.maps.LatLng(52.136436, -0.460739));
map.setZoom(13);
return;
}
map.fitBounds(bounds);
if(markers.length === 1){
map.setZoom(13);
}
});
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="width:300px; height: 500px; float:right; padding-left:10px; padding-right:10px; margin: 50px 90px 50px 75px">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" align="center" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
Reference
<input type="text" id="reference">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
<div id="menu" style=" position: absolute; margin: 45px 89px;" >
<select id="Counties">
<option value="">Select County</option>
<option value="bedfordshire">Bedfordshire</option>
<option value="buckinghamshire">Buckinghamshire</option>
<option value="cambridgeshire">Cambridgeshire</option>
<option value="hertfordshire">Hertfordshire</option>
<option value="northamptonshire">Northamptonshire</option>
</select>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right; margin:20px 75px;"></div>
<div id="supplementwindow" style="border:1px solid #ccc; background:#e5e5e5; align-content:center; float:left; position:absolute; margin:200px 0px 200px 200px; padding: 5px; border-radius: 12px;" >
<input type="button" value="Assign">
</div>
<div id="menu2" style="position: absolute; right: 200px; top: 450px; border: 1px solid #bbb; padding: 5px;
border-radius: 12px;"><select id="themarkers"><option value="">Select Marker</option>
</select><br>
<input type="button" id="showall" title="Or Reset if None" value="Show All"><br>
<input type="button" id="removemarker" value="Remove Marker"></div>
</body>
</html>
The snippet of my code below is where I am trying to embed the KML file as a layer. I have tried using an online server URL with my KML and it doesn't work and also using Wamp as a local host server. Would it actually work with Wamp?
Have I placed to coding in the wrong place, have I written it wrong or missed out something? If anyone could give me some guidance, I would appreciate it thanks.
var ctaLayer = new google.maps.KmlLayer({
url: 'file:///C|/wamp/www/maps/UK County border lines.kml',
map: map
});
According to the documentation, the KmlLayer URL must be publicly accessible.
Overview
The Google Maps JavaScript API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var kmlLayer = new google.maps.KmlLayer({
map: map,
url: "http://www.geocodezip.com/geoxml3_test/final_map_original_wales1c.xml"
})
google.maps.event.addListener(kmlLayer, 'status_changed', function() {
document.getElementById('status').innerHTML = "KmlStatus=" + kmlLayer.getStatus();
})
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="status"></div>
<div id="map_canvas"></div>
so far the text is centered the google maps page hugs the left and then the text underneath it remains centered, i just want the map to be centered.
<div id="row1">
<div id="note"><img src="http://www.bristol.gov.uk/sites/default/files/styles/hero_image/public/images/children_and_young_people/resources_for_professionals/head_teachers_and_school_administrators/hr/contact_us/we%20will%20be%20back%20soon-sticky%20note.jpg?itok=08vLR_lO"></div>
<div id = "hours">
Sorry<br>
hours<br>
</div>
<div id="gmap_canvas" style="height:500px; width:600px;"></div>
Below text
</div>
Style:
#row1 {
text-align: center;
}
Google Map JavaScript:
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 16,
center: new google.maps.LatLng(20.0820037, -14.26733380000002),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(20.0820037, -14.26733380000002)
});
infowindow = new google.maps.InfoWindow({
content: "<b>Crokson Dine In</b><br/>43 Gill Rd<br/>09521 Hovill"
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
text-align: center cannot center a block element itself. You need auto margins:
<div
id="gmap_canvas"
style="height:500px; width:600px; margin-left: auto; margin-right: auto;">
Till now..I had been passing a source and a destination value inside a direction service object which will draw a route between a source and a destination. But here i am receiving an array of latitude and longitude which i need to pass it inside a direction service object.
Eg: I have four places Like New York, Washington, Manhatten,
California. So i should be able to draw a route from New York To
California Where the route passes from Washington and Manhatten and
have only two markers. A Marker for New York and B marker for
California.
I tried making use of way points. But in my example it makes use of place names and not latitude and longitudes. Morever it creates marker for every place it visits.
My requirement is to pass latitude and longitude in array and draw the
route using directionservice.
Please find the below code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Chart</title>
<style>
html,body,#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var directionsDisplay; var directionsService = new google.maps.DirectionsService();
var map;
function initialize()
{
directionsDisplay = new google.maps.DirectionsRenderer();
var delhi = new google.maps.LatLng(28.6168, 77.2434);
var mapOptions =
{
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: delhi
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++)
{ if (checkboxArray.options[i].selected == true)
{
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request =
{
origin: start,
destination: end,
waypoints: waypts,
provideRouteAlternatives:true,
// alternatives:true,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
var polylineOptions = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 2
});
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = ''; // For each route, display summary information.
for (var i = 0; i < route.legs.length; i++)
{
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} });
}
google.maps.event.addDomListener(window, 'load', initialize); </script>
</head>
<body>
<div id="map-canvas" style="float: left; width: 70%; height: 100%;"></div>
<div id="control_panel"
style="float: right; width: 30%; text-align: left; padding-top: 20px">
<div style="margin: 20px; border-width: 2px;"><b>Loco Journey Start Station:</b> <select
id="start">
<option value="Tughlakabad">Tughlakabad</option>
<option value="Lucknow">Lucknow</option>
<option value="Firozpur">Firozpur</option>
<option value="Ghaziabad">Ghaziabad</option>
</select> <br>
<b>Journey:</b> <br>
<i>(Ctrl-Click for multiple selection)</i> <br>
<select multiple id="waypoints">
<option value="Bhopal">Bhopal</input>
<option value="Raipur">Raipur</input>
<option value="Farukkhabad">Farukkhabad</input>
<option value="Jhansi">Jhansi</input>
</select> <br>
<b>Loco Journey End Station:</b> <select id="end">
<option value="Lucknow">Lucknow</option>
<option value="Firozpur">Firozpur</option>
<option value="Ghaziabad">Ghaziabad</option>
<option value="Tughlakabad">Tughlakabad</option>
</select> <br>
<input type="submit" onclick="calcRoute();"></div>
<div id="directions_panel"
style="margin: 20px; background-color: #FFEE77;"></div>
</div>
</body>
</html>
The DirectionsRequest:
Takes either a string (for an address) or a google.maps.LatLng object (for coordinates).
origin | LatLng|string | Location of origin. This can be specified as either a string to be geocoded or a LatLng. Required.
destination | LatLng|string | Location of destination. This can be specified as either a string to be geocoded or a LatLng. Required.
Waypoints take a boolean "stopover" flag which determines where or not they get a marker. Set it to false. It can also take either a string (for an address) or a google.maps.LatLng object (for coordinates) in the location property.
stopover | boolean | If true, indicates that this waypoint is a stop between the origin and destination. This has the effect of splitting the route into two. This value is true by default. Optional.
I have This Map I am working on and it opens at San Francisco. I would like to change this to open at a specified town, country of my choice. (i.e. London, England or Javea, Spain) The location changes on every page of my site and the "Town & Country" are inserted in the page from a database.
Example: {$listing_city} = Town {$listing_country} = Country
The search box at the top is not needed as I want to show the local restaurants, bars, doctors in that area. However, the search box can stay I just want the map to open in the respective town.
I am new hear and wondered if anyone can help.
Thanks in advance
Mal
<!DOCTYPE html>
<html>
<head>
<title>Google Developers</title>
<link rel="stylesheet" type="text/css" href="/_static/css/screen.css" />
<link rel="stylesheet" href="//www.google.com/cse/style/look/default.css" type="text/css" />
<link href='//fonts.googleapis.com/css?family=Open+Sans:300,400' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script id="jqueryui" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js" defer async></script>
<script src="//www.google.com/jsapi?key=AIzaSyCrlr1LScCevQ1epeHArLVww0eHlB6o1wg"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="docs framebox_body">
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var map, places, iw;
var markers = [];
var autocomplete;
function initialize() {
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
google.maps.event.addListener(autocomplete, 'place_changed', function() {
showSelectedPlace();
});
}
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', search);
google.maps.event.addListener(map, 'dragend', search);
search();
}
function showSelectedPlace() {
clearResults();
clearMarkers();
var place = autocomplete.getPlace();
map.panTo(place.geometry.location);
markers[0] = new google.maps.Marker({
position: place.geometry.location,
map: map
});
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[0]);
}
function search() {
var type;
for (var i = 0; i < document.controls.type.length; i++) {
if (document.controls.type[i].checked) {
type = document.controls.type[i].value;
}
}
autocomplete.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
if (type != 'establishment') {
search.types = [type];
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
for (var i = 0; i < results.length; i++) {
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
markers[i] == null;
}
}
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
}
}
function addResult(result, i) {
var results = document.getElementById('results');
var tr = document.createElement('tr');
tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = result.icon.replace('http:', '');
icon.setAttribute('class', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = '<table style="border:0"><tr><td style="border:0;">';
content += '<img class="placeIcon" src="' + place.icon + '"></td>';
content += '<td style="border:0;"><b>' + place.name + '</b>';
content += '</td></tr></table>';
return content;
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%;
font-family: arial;
font-size: 13px;
overflow: hidden;
}
#map_canvas {
float: left;
width: 420px;
height: 406px;
}
#listing {
float: left;
margin-left: 1px;
width: 210px;
height: 406px;
overflow: auto;
cursor: pointer;
}
#controls {
padding: 5px;
}
.placeIcon {
width: 16px;
height: 16px;
margin: 2px;
}
#results {
border-collapse: collapse;
width: 184px;
}
#locationField {
margin-left: 1px;
}
#autocomplete {
width: 516px;
border: 1px solid #ccc;
}
</style>
<div id="locationField">
<input id="autocomplete" type="text">
</div>
<div id="map_canvas"></div>
<div id="listing">
<div id="controls">
<form name="controls">
<!--<input type="radio" name="type" value="establishment" onclick="search()" checked="checked"/>All<br/>-->
<input type="radio" name="type" value="restaurant" onclick="search()" />Restaurants<br/>
<input type="radio" name="type" value="police" onclick="search()" />Police Station<br/>
<input type="radio" name="type" value="church" onclick="search()" />Churches<br/>
<input type="radio" name="type" value="doctor" onclick="search()" />Doctor<br/>
<input type="radio" name="type" value="bar" onclick="search()" />Bars<br/>
<input type="radio" name="type" value="bank" onclick="search()" />Banks<br/>
</form>
</div>
<table id="results"></table>
</div>
</body>
</html>
You have to know latitude of towns you want. Than on every page you need to change this lines in initialize() function from
var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
to
var myLatlng = new google.maps.LatLng(changeTHIS, andTHIS);
here is example for London
var myLatlng = new google.maps.LatLng(51.507222, -0.1275);