Combine InfoWindow data when overlapping polygons clicked? - google-maps

Is it possible to combine all polygon data (description & name) at a specific point into one InfoWindow when clicked? I have some overlapping polygons and the InfoWindow only displays the data from the topmost one. It seems this should be possible using Fusion Tables and a click listener on the map so that when someone clicks on the map, a query is sent to Fusion Tables to find all the Polygons that intersect with the point that was clicked (using ST_INTERSECTS with a CIRCLE and a very small radius). The only columns in my Fusion Table are Name, Description, and Geometry (containing standard KML ).
This is as far as I am with it. Polygons are displaying and circle is being rendered and centered onclick. InfoWindow is displaying [object Object].
var lat = 37.4;
var lng = -122.1;
var tableid = '1mxcz4IDL1U7ItrqulVzt01fMasj5zsmBFUuQh6iM';
var meters = 10000;
layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: tableid,
}
});
layer.setMap(map);
google.maps.event.addListener(layer, 'click', function(event) {
changeCenter(event);
});
function changeCenter(event) {
lat = event.latLng.lat();
lng = event.latLng.lng();
circle.setCenter(event.latLng);
}
circle = new google.maps.Circle({
center: new google.maps.LatLng(lat, lng),
radius: meters,
map: map,
fillOpacity: 0.2,
strokeOpacity: 0.5,
strokeWeight: 1,
});
comboname = new google.maps.FusionTablesLayer({
query: {
select: 'name',
from: tableid,
where: 'ST_INTERSECTS(geometry, CIRCLE(LATLNG(' + lat + ',' + lng + '),' + meters + '))'
}
});
google.maps.event.addListener(layer, 'click', function(e) {
// Display all of the names in the InfoWindow
e.infoWindowHtml = comboname;
});
}

A FusionTablesLayer doesn't provide any data related to the displayed features.
When you want to get data from the FusionTable you must request them via the REST-API (this also happens when the API will open an InfoWindow, when you take a look at the Network-Traffic you'll see that there is a request which loads the data for the InfoWindow).
The REST-API supports JSONP, so you may request the data directly via JS.
Requirements for SELECT
a valid google-API-key
the service Fusion Tables API must be enabled for the project
The FusionTable must be configured as downloadable (the table in your example already is downloadable)
Sample-implementation:
function initialize() {
var goo = google.maps,
//your google maps API-key
gooKey = 'someGoogleApiKey',
//FusionTable-ID
ftId = '1mxcz4IDL1U7ItrqulVzt01fMasj5zsmBFUuQh6iM',
//1km should be sufficient
meters = 1000,
map = new goo.Map(document.getElementById('map_canvas'),
{
zoom: 6,
center: new goo.LatLng(36.8,-111)
}),
//we use our own InfoWindow
win = new goo.InfoWindow;
//function to load ft-data via JSONP
ftQuery = function(query,callback){
//a random name for a global function
var fnc = 'ftCallback'+ new Date().getTime()
+ Math.round(Math.random()*10000),
url = 'https://www.googleapis.com/fusiontables/v2/query?',
params = {
sql : query,
callback : fnc,
key : gooKey
},
get =[],
script = document.querySelector('head')
.appendChild(document.createElement('script'));
for(var k in params){
get.push([encodeURIComponent(k),
encodeURIComponent(params[k])
].join('='));
}
window[fnc]=function(r){
callback(r);
delete window[fnc];
document.querySelector('head').removeChild(script);
}
script.setAttribute('src',url+get.join('&'));
},
ftLayer = new goo.FusionTablesLayer({
query: {
select: 'geometry',
from: ftId,
},
map:map,
suppressInfoWindows:true
});
goo.event.addListener(ftLayer,'click',function(e){
var sql ='SELECT name FROM ' + ftId +
' WHERE ST_INTERSECTS(geometry,'+
' CIRCLE(LATLNG(' +e.latLng.toUrlValue()+ '),'+ meters + '))',
cb = function(response){
if(response.error){
try{
alert(response.error.errors[0].message);
}
catch(e){
alert('error while retrieving data from fusion table');
}
return;
}
var content = [];
for(var r = 0; r < response.rows.length; ++r){
content.push(response.rows[r][0]);
}
//open the infowindow with the desired content
win.setOptions({
content:'<ol><li>'+content.join('</li><li>')+'</li></ol>',
map:map,
position:e.latLng
});
};
ftQuery(sql,cb);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Demo: http://jsfiddle.net/doktormolle/ckyk4oct/

Related

Dynamic Load of Heatmap Data based on Map Bounds, Performance Issue

I have implemented a simple page that uses a listener to determine when a google maps bounds have changed because of zoom or pan. I am dynamically loading json data for a weighted heatmap summarized by the area visible in the map. It is working all except for the fact that I am not properly clearing the previous data from the heatmap on each call to the listener. Performance begins to degrade after the 4th or 5th call to fetch new data. I tried setting heatmap to null. What else is needed to maintain performance?
var map, heatmap;
var heatMapData = [];
function initMap() {
var uluru = { lat: 32.673363, lng: -97.399290 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: uluru
});
google.maps.event.addListener(map, "bounds_changed", function () {
heatmap = null;
var bounds = map.getBounds();
//TODO: implement async request
var Httpreq = new XMLHttpRequest(); // a new request
var boxRequest = 'HeatMapData?lmin=' + bounds.f.f + '&lmax=' + bounds.f.b + '&lnmin=' + bounds.b.b + '&lnmax=' + bounds.b.f;
Httpreq.open("GET", boxRequest, false);
Httpreq.setRequestHeader("Content-type", "application/json")
var heatMapJSON = Httpreq.responseText;
heatMapData = [];
var parsedJSON = JSON.parse(heatMapJSON);
for (var i = 0; i < parsedJSON.length; i++) {
heatMapData.push({ location: new google.maps.LatLng(parsedJSON[i].Lat, parsedJSON[i].Lon), weight: parsedJSON[i].weight })
};
console.info('map points: ' + parsedJSON.length.toString());
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
map : map
});
});
if (heatmap != null) {
heatmap.setMap(null);
};

Can't load markers into Google Maps API from JSON

Thanks in advance for any help you can provide! I'm trying to create markers in my Google Map using JSON data. The good news is that I've got the data in the format I need it. The bad news is that I'm new to JSON, and I can't seem to get the markers to show up on the map. From the console's response, the issue seems to be the mapInit line at the bottom of the code below.
I have tried resolving this problem by reviewing solutions at different markers on google maps v3, Using JSON markers in Google Maps API with Javascript, and Google Maps API v3: Adding markers from an array doesn't work, among others. I've also tried duplicating the examples at http://weareallrobots.com/demos/map.html and other sites, but I'm still having trouble.
My code:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
// HERE'S WHERE PROBLEMS START
$.getJSON("mapall.js", {}, function(data){
$.each(data.masterlocation, function(i, item){
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.latitude, item.longitude),
map: map_canvas,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
UNRELATED ROUTING CODE HERE
}
// HERE'S WHERE MORE PROBLEMS START
$(function(){
// initialize map (create markers, infowindows and list)
mapInit();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
</script>
My JSON Data
[{"masterlocation":{"latitude":"33.5","nickname":"First","longitude":"-86.8"}},{"masterlocation":{"latitude":"34.7","nickname":"Second","longitude":"-86.6"}},
UPDATE 1
As per comments from geocodezip and Adam, I've updated my code to the below. I added the + symbol before latitude and longitude, and I replaced mapInit with initialize. However, I'm still not getting any markers to show up. Firebug is telling me that I have errors in my jQuery file, but I'm not sure if these are related. Thanks for sticking with me!
Code:
// HERE'S WHERE PROBLEMS START
$.getJSON("mapall.js", {}, function(data){
$.each(data.masterlocation, function(i, item){
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+item.latitude, +item.longitude),
map: map_canvas,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
UNRELATED ROUTING CODE HERE
}
// HERE'S WHERE MORE PROBLEMS START
$(function(){
// initialize map (create markers, infowindows and list)
initialize();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
JQuery errors
TypeError: a is undefined
[Break On This Error]
...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...
jquery.js (line 29)
TypeError: a is undefined
[Break On This Error]
...rn a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){...
UPDATE 2
My current code is below, as well as the error codes I am getting in the console. New errors appeared when I reloaded the page, and they refer to the line in my javascript where function initialize first occurs. Maybe this is the problem?
Also, is it possible that the problem is in the JSON? Each JSON entry is preceded by the name of the MYSQL table, "Masterlocation" (see above.) In other JSON examples I've seen, the term that comes after the "." in "$.each(data.masterlocation)" only occurs once.
My Javascript:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var rendererOptions = {
draggable: true,
panel:document.getElementById('directions_panel')
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 6,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
$.getJSON("mapall.js", {}, function(data){
console.log(data);
$.each(data.masterlocation, function(i, item){
console.log(item);
$("#markers").append('<li>' + item.nickname + '</li>');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(+item.latitude, +item.longitude),
map: map,
title: item.nickname
});
arrMarkers[i] = marker;
var infowindow = new google.maps.InfoWindow({
content: "<h3>"+ item.nickname +"</h3>"
});
arrInfoWindows[i] = infowindow;
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
});
}
function calcRoute() {
ROUTING CODE
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: optimize,
travelMode: google.maps.TravelMode.DRIVING
};
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");
}
$(function(){
// initialize map (create markers, infowindows and list)
initialize();
// "live" bind click event
$("#markers a").live("click", function(){
var i = $(this).attr("rel");
// this next line closes all open infowindows before opening the selected one
//for(x=0; x < arrInfoWindows.length; x++){ arrInfoWindows[x].close(); }
arrInfoWindows[i].open(map, arrMarkers[i]);
});
});
</script>
Javascript Errors from Console: these only occurred after I reloaded the page.
Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
c.extend.each jquery.js:29
(anonymous function) mapall:87
b jquery.js:121
w.onreadystatechange jquery.js:127
Uncaught TypeError: Cannot read property 'length' of undefined jquery.js:29
c.extend.each jquery.js:29
(anonymous function) mapall:87
b jquery.js:121
w.onreadystatechange jquery.js:127
In addition to any other errors, the way you're accessing the JSON data doesn't match the format of that data.
Your code to access the JSON data is:
$.getJSON( "mapall.js", {}, function( data ) {
$.each( data.masterlocation, function( i, item ) {
... use item.nickname, item.latitude, and item.longitude here
});
});
Now there's nothing wrong with that code, if the JSON data looked like this:
{
"masterlocation": [
{
"nickname": "First",
"latitude": 33.5,
"longitude": -86.8
},
{
"nickname": "Second",
"latitude": 34.7,
"longitude": -86.6
}
]
}
This JSON data is an object with a single property named masterlocation. That property is an array of objects, each one containing nickname, a string, and latitude and longitude, two numbers.
That's a pretty sensible way to lay out the JSON data. I would do it just about the same myself. (The only things I can think of changing would be the naming conventions: I'd probably use a name like locations instead of masterlocation because I like to see plural names for arrays, and I like shorter names for commonly-used properties, e.g. name, lat, and lng. But that's purely a matter of style—the structure I'd use is identical aside for names.)
Unfortunately, your actual JSON data looks like this:
[
{
"masterlocation": {
"latitude": "33.5",
"nickname": "First",
"longitude": "-86.8"
}
},
{
"masterlocation": {
"latitude": "34.7",
"nickname": "Second",
"longitude": "-86.6"
}
}
]
This is an array of two elements. Each element is an object with one property named masterlocation. Each masterlocation object contains the nickname, latitude, and longitude properties. And the latitude and longitude are strings instead of numbers like they should be.
It would be easy enough to change your code to work with this structure:
$.getJSON( "mapall.js", {}, function( data ) {
$.each( data, function( i, item ) {
var loc = item.masterlocation;
... use loc.nickname, +loc.latitude, and +loc.longitude here
});
});
But if you have the option of changing the format of your JSON format, I'd do that instead. You had the right idea in your JavaScript code, just change the JSON output to match.
Make sure the latitude and longitude are actually numbers in JS, not strings.
To do a type convert, just put a + in front of the string
position: new google.maps.LatLng(+item.latitude, +item.longitude)
For some reason, google's API was not built smart enough to handle passing in strings containing numbers....go figure.
EDIT
Ditto to the comment on your post as well - you are calling a function mapInit() but you should be calling the function initialize() from the looks of it.
EDIT2
This line:
map: map_canvas,
should be
map: map,

Adding Google Maps V3 User input through a searchbox

So, I found some instructions around and a few questions that seemed to answer this question, but none really worked for me or were very incomplete. I'm seeking a way to display the traditional google maps interaction of search and a pin is displayed on the map at the location. This marker, then, should be a blank option to include the data a user wants and the location saved to my database. I tried this sample by Google Dev and it worked for a custom click on the map, but the integration with a simple auto-complete search or even the google's own autocomplete search didn't quite worked.
I was wondering if there is a plugin or a technique (or a tutorial) that would suit this case (that I previously thought would be a simple matter as it is the traditional search on google maps). Thanks!
I can show you how I did this page http://www.a-zhotels.net/register, you could easily combine all the fields into one autocomplete address field. However, this should give you an idea.
First, create a function:
function getMapByGeoLocation() {
//build the address using many fields.
var postcode = $("#HotelPostcode").val();
var address = $("#HotelAddress").val();
var town = $("#HotelTown").val();
var city = $("#HotelCity").val();
var country = $("#HotelCountryId > option:selected").text();
var fulladdress = address + ', ' + town + ', ' + postcode + ', ' + city + ', ' + country;
geocoder.geocode(
{
'address': fulladdress
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
console.log(location);
//map and marker should be previously created
map.setCenter(location);
map.setZoom(14);
marker.setPosition(location);
//These 2 hidden inputs will be posted to the server
$("#HotelLatitude").val(location.Ya);
$("#HotelLongitude").val(location.Za);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
This function is then called when the textbox and dropdowns change:
$("#HotelTown, #HotelAddress, #HotelPostcode").change(getMapByGeoLocation);
See below the function that creates the map:
var map;
var marker;
var geocoder;
function createMap() {
if (map) { //Map already exists
return;
}
if (!$('#mapCanvas').is(':visible')) {
return;
}
var mapCanvas = $("#mapCanvas")[0];
var averageLatitude = $("#HotelLatitude").val();
var averageLongitude = $("#HotelLongitude").val();
map = new google.maps.Map(mapCanvas, {
streetViewControl: true,
zoom: 13,
scrollwheel: false,
center: new google.maps.LatLng(averageLatitude, averageLongitude)
});
geocoder = new google.maps.Geocoder();
//Associate the styled map with the MapTypeId and set it to display.
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
marker = new google.maps.Marker({
position: new google.maps.LatLng(averageLatitude, averageLongitude),
draggable: true,
map: map
});
google.maps.event.addListener(marker, "dragend", function () {
var position = marker.getPosition();
map.panTo(position);
$("#HotelLatitude").val(position.lat());
$("#HotelLongitude").val(position.lng());
});
google.maps.event.addListener(map, "center_changed", function () {
var position = map.getCenter();
marker.setPosition(position);
$("#HotelLatitude").val(position.lat());
$("#HotelLongitude").val(position.lng());
});
}
createMap();
I am not sure what exactly you are looking for.
If you are looking for autocomplete field that adds a marker to the map after the user entered some string and opens an infowindow with a form on the map, is may be something like that: http://jsfiddle.net/XG9Qj/2/
It is important to notice, that this example only places a marker on the map if the user selected one of the suggestions from the autocomplete. To allow him to enter an arbitrary string you have to watch the input for RETURN and use the google maps geocoder on your own(1).
var geocoder = new google.maps.Geocoder();
geocoder.geocode(...)

How can I check if google map is already loaded

I am working in a project to provide a map to mobile phone. For now I am trying on a iPhone.
It works fine, and when I load my first page I can see a map with my position, and the market is refreshed each 10 sec and move to my next position.
Some time when I change of page and I come back to the first page, the map is not full displayed. If I move the map, it move but some image of the map is still not displayed.
Also I am working with jquery mobe.
I also noticed that each time I return to the first map, the map is reloaded.
Is there a way to load the map once?
So how can i check that my map is already loaded?
Here is my code
$('#home').live('pagebeforeshow', function(e){
// Resize #mapHome (#mapHome = Sreen hight - footer - header)
$('#mapHome').css('height', Resize.content()-2 +'px');
// extract les id des modules existants
navigator.geolocation.getCurrentPosition(function(position){
showMap('mapHome',position.coords.latitude, position.coords.longitude);
//console.log(position.coords.latitude, position.coords.longitude);
},
function(){
//error
},
{
enableHighAccuracy : true,
maximumAge : 30000
//maximumAge:Infinity
});
// Place and move the marker regarding to my position and deplacement
var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
console.log('WatchPosition called');
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
})
I just changed that line to
$('#home').live('pageshow', function(e){... code...}
And it semas to be better but I am not sure-
Here is the code of my function showMap()
function showMap(canvas,lat,long){
var latLng = new google.maps.LatLng(lat,long);
// Google Map options var myOptions = {
zoom: 19,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN };
// Create the Google Map, set options Tracking.mapy = new google.maps.Map(document.getElementById(canvas), myOptions);
}
And here is the code addMarker()
function addMarker(lat, long){
Tracking.mapBounds = new google.maps.LatLngBounds();
// Clean previous markers
for (var i = 0; i < Tracking.markers.length; i++ ) {
Tracking.markers[i].setMap(null);
}
// Add the owner's marker
var latitudeAndLongitude = new google.maps.LatLng(lat, long);
var image = "img/iconGoogleMap/phones.png";
marker = new google.maps.Marker({
title : 'me',
//animation: google.maps.Animation.DROP, //BOUNCE
position: latitudeAndLongitude,
map : Tracking.mapy,
icon : image
});
Tracking.markers.push(marker);
//Tracking.markers.push(marker);
//console.log(localStorage.getItem('mapToDisplay'));
/* ADDING MODULES MAKERS */
// Store the ID of available module.
modulesJSON = Modules.get('bipme');
for (var i = 0; i < modulesJSON['modules'].length; i++) {
console.log('module id = ' +modulesJSON['modules'][i].id);
console.log('Module ' + modulesJSON['modules'][i].id + ' position : ' + ModulesPos.module(modulesJSON['modules'][i].id));
nlatLong = ModulesPos.module(modulesJSON['modules'][i].id).split(",");
var LatitudeAndLongitudeModules = new google.maps.LatLng(nlatLong[0],nlatLong[1]);
var image = "img/iconGoogleMap/" + modulesJSON['modules'][i].profile + "-" + modulesJSON['modules'][i].iconColor + ".png";
marker = new google.maps.Marker({
title : modulesJSON['modules'][i].pseudo,
//animation: google.maps.Animation.DROP, //BOUNCE
position: LatitudeAndLongitudeModules,
map : Tracking.mapy,
icon : image
});
Tracking.mapBounds.extend(LatitudeAndLongitudeModules);
Tracking.markers.push(marker);
};
By the way, is there a way to create a button, from which I can manually refresh the map?

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.