Google map reset to initial state - google-maps

I'm trying to find out how to add a "reset to initial state"-button.
I have a Google Map with markers for a few shop locations.
This is the code I use:
<script type="text/javascript">
(function($) {
/** new_map */
function new_map( $el ) {
// var
var $markers = $el.find('.marker');
// vars
// vars
var args = {
zoom: 15,
center: new google.maps.LatLng(0, 0),
mapTypeControl: false,
panControl: false,
scrollwheel: false,
streetViewControl:false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
styles: [{"stylers":[{"saturation":-100},{"gamma":1}]},{"elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.text","stylers":[{"visibility":"off"}]},{"featureType":"poi.place_of_worship","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"saturation":50},{"gamma":0},{"hue":"#50a5d1"}]},{"featureType":"administrative.neighborhood","elementType":"labels.text.fill","stylers":[{"color":"#333333"}]},{"featureType":"road.local","elementType":"labels.text","stylers":[{"weight":0.5},{"color":"#333333"}]},{"featureType":"transit.station","elementType":"labels.icon","stylers":[{"gamma":1},{"saturation":50}]}]};
// create map
var map = new google.maps.Map( $el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function(){
add_marker( $(this), map );
});
// center map
center_map( map );
// return
return map;
}
// create info window outside of each - then tell that singular infowindow to swap content based on click
var infowindow = new google.maps.InfoWindow({
content : ''
});
/** add_marker */
function add_marker( $marker, map ) {
// var
var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
// create marker
var marker = new google.maps.Marker({
position : latlng,
map : map
});
// add to array
map.markers.push( marker );
// if marker contains HTML, add it to an infoWindow
if( $marker.html() )
{
// create info window
liTag=$(".aflista ul").find("[data-lat='" + $marker.attr('data-lat') + "']");
// console.log(liTag);
// show info window when marker is clicked
$(liTag).click(function() {
infowindow.setContent($marker.html());
infowindow.open(map, marker);
map.setZoom(12);
map.setCenter(marker.getPosition())
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent($marker.html());
infowindow.open(map, marker);
map.setZoom(12);
map.setCenter(marker.getPosition())
});
// close info window when map is clicked
google.maps.event.addListener(map, 'click', function(event) {
if (infowindow) {
infowindow.close(); }
});
}
}
/** center_map */
function center_map( map ) {
// vars
var bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each( map.markers, function( i, marker ){
var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
bounds.extend( latlng );
});
// only 1 marker?
if( map.markers.length == 1 )
{
// set center of map
map.setCenter( bounds.getCenter() );
map.setZoom( 16 );
}
else
{
// fit to bounds
map.fitBounds( bounds );
}
}
/** document ready */
// global var
var map = null;
$(document).ready(function(){
$('.acf-map').each(function(){
// create map
map = new_map( $(this) );
});
});
})(jQuery);
Now I want to add a button anywhere outside or inside the map only to have the option to reset the zoom and center to the initial state.
Any points in the right direction would be awesome.
Thanks!

To reset the map to its initial state, do the same thing you do when you initialize your map. You don't need to redo everything, you can save the computed initial bounds in a global variable (as well as the map), then call map.fitBounds(bounds); when your reset button is clicked.
$("#reset_state").click(function() {
infowindow.close();
map.fitBounds(bounds);
})
proof of concept fiddle
code snippet:
(function($) {
/** new_map */
function new_map($el) {
var $markers = $el.find('.marker');
var args = {
zoom: 15,
center: new google.maps.LatLng(0, 0),
mapTypeControl: false,
panControl: false,
scrollwheel: false,
streetViewControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
}
};
// create map
map = new google.maps.Map($el[0], args);
// add a markers reference
map.markers = [];
// add markers
$markers.each(function() {
add_marker($(this), map);
});
// center map
center_map(map);
// return
return map;
}
// create info window outside of each - then tell that singular infowindow to swap content based on click
var infowindow = new google.maps.InfoWindow({
content: ''
});
/** add_marker */
function add_marker($marker, map) {
// var
var latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));
// create marker
var marker = new google.maps.Marker({
position: latlng,
map: map
});
// add to array
map.markers.push(marker);
// if marker contains HTML, add it to an infoWindow
if ($marker.html()) {
// create info window
liTag = $(".aflista ul").find("[data-lat='" + $marker.attr('data-lat') + "']");
// console.log(liTag);
// show info window when marker is clicked
$(liTag).click(function() {
infowindow.setContent($marker.html());
infowindow.open(map, marker);
map.setZoom(12);
map.setCenter(marker.getPosition())
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent($marker.html());
infowindow.open(map, marker);
map.setZoom(12);
map.setCenter(marker.getPosition())
});
// close info window when map is clicked
google.maps.event.addListener(map, 'click', function(event) {
if (infowindow) {
infowindow.close();
}
});
}
}
/** center_map */
function center_map(map) {
// vars
bounds = new google.maps.LatLngBounds();
// loop through all markers and create bounds
$.each(map.markers, function(i, marker) {
var latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
bounds.extend(latlng);
});
// only 1 marker?
if (map.markers.length == 1) {
// set center of map
map.setCenter(bounds.getCenter());
map.setZoom(16);
} else {
// fit to bounds
map.fitBounds(bounds);
}
}
/** document ready */
// global var
var map = null;
var bounds = null;
$(document).ready(function() {
$('.acf-map').each(function() {
// create map
map = new_map($(this));
});
$("#reset_state").click(function() {
infowindow.close();
map.fitBounds(bounds);
})
});
})(jQuery);
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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" id="reset_state" value="reset" />
<div class="aflista">
<ul>Markers
<li data-lat='40.7127837'>New York, NY</li>
<li data-lat='40.735657'>Newark, NJ</li>
</ul>
</div>
<div class="acf-map" id="map_canvas">
<div class="marker" data-lat="40.7127837" data-lng="-74.00594130000002" data-title="New York, NY">New York, NY</div>
<div class="marker" data-lat="40.735657" data-lng="-74.1723667" data-title="Newark, NJ">Newark, NJ</div>
</div>

Related

Issue to set map in center so multiple marker display

i am using ionic framework. i created map and multiple markers and value came from server side.all data came properly but i don't know why i getting this error-
ionic.bundle.js:25642 TypeError: Cannot read property 'fitBounds' of null
at autoCenter (app.js:147)
at app.js:135
at processQueue (ionic.bundle.js:27879)
at ionic.bundle.js:27895
at Scope.$eval (ionic.bundle.js:29158)
at Scope.$digest (ionic.bundle.js:28969)
at Scope.$apply (ionic.bundle.js:29263)
at done (ionic.bundle.js:23676)
at completeRequest (ionic.bundle.js:23848)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:23789)
code :
angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function ($http) {
var markers = [];
return {
getMarkers: function () {
return $http.get("http://localhost:8080/LocationServices/markers.php").then(function (response) {
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function ($cordovaGeolocation, Markers) {
var apiKey = false;
var map = null;
var zoomVal = 15
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true };
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Latitude current: ", position.coords.latitude);
console.log("Longitude current: ", position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function () {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: latLng
});
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}, function (error) {
console.log("Could not get location");
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}
function loadMarkers(map) {
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function (markers) {
console.log("Markers: ", markers);
var markersss = new Array();
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
console.log("Latitude: ", record.lat);
console.log("Longitude: ", record.lng);
var markerPos = new google.maps.LatLng(record.lat, record.lng);
console.log("marker position", "" + markerPos);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
markersss.push(marker);
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
autoCenter(map, markersss);
});
}
function autoCenter(map1, markersss) {
//Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
//Go through each...
for (var i = 0; i < markersss.length; i++) {
bounds.extend(markersss[i].position);
console.log("bounds position", "" + markersss[i].position);
}
//Fit these bounds to the map
map1.fitBounds(bounds);
map1.setCenter(bounds.getCenter());
//remove one zoom level to ensure no marker is on the edge.
map1.setZoom(vm.googleMap.getZoom() - 1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if (map1.getZoom() > zoomVal) {
map1.setZoom(zoomVal);
}
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function () {
initMap();
}
}
})
.controller('MapCtrl', function ($scope, $state, $cordovaGeolocation) {
});
The map will only be created when $cordovaGeolocation.getCurrentPosition was successfull, but you also call loadMarkers when it wasn't successfull(map is null in this case)
Solution: create the map outside of the getCurrentPosition-callbacks (with a default-value for center).
In the success-callback create the marker and set the center of the map
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true },
mapOptions = {
center: new google.maps.LatLng(-37.92,151.25),
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function () {
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var center = new google.maps.LatLng( position.coords.latitude,
position.coords.longitude);
map.setCenter(center);
new google.maps.Marker({
map : map,
animation : google.maps.Animation.DROP,
position : center
});
loadMarkers(map);
}, function (error) {
loadMarkers(map);
});
});
}

Google Maps API - Activating the infowindow of a custom marker

I am trying to activate the infowindow for a custom marer, yielding a small description about the marker, I'm having some trouble at the moment, I have the custom marker working but I can't get the infowindow to show.
I tried calling the listener for the marker and storing it in a variable "customMarker", then calling another mouseover listener to activate the infowindow, but I'm having no luck, can anyone help me out?
var map;
//Creates a custom icon to be placed on the map
var goldStar = 'https://cdn2.iconfinder.com/data/icons/august/PNG/Star%20Gold.png';
function initialize() {
//Sets the zoom amount for the map, the higher the number, the closer the zoom amount
var mapOptions = {
zoom: 18
//center : myLatLng
};
//The map object itself
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Tries to find user location using HTML 5
if(navigator.geolocation)
{
//sets the map to the position of the user using location
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
//This listener is not working
//google.maps.event.addListener(customMarker, 'mouseover', function() {
//infowindow.open(map,customMarker);
//});
}
function placeMarker(location, map)
{
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable:true
});
map.panTo(location);
}
The google.maps.event.addListener function does not return a marker. This won't work:
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
Assign the event listener in your placeMarker function to the marker you create (also gives the advantage of maintaining function closure on the marker):
function placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable: true
});
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
map.panTo(location);
}
working fiddle

Google maps adding streetview to each infowindow

I would like to add streetview to each infowindow but I can't figure out how to integrate the code. I tried putting the code where the comments are set and that works half. Still have to learn a lot about programming.
html += '<div id="content" style="width:200px;height:200px;"></div>';
var pano = null;
google.maps.event.addListener(infoWindow, 'domready', function () {
if (pano != null) {
pano.unbind("position");
pano.setVisible(false);
}
pano = new google.maps.StreetViewPanorama(document.getElementById("content"), {
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.ANDROID },
enableCloseButton: false,
addressControl: false,
linksControl: false
});
pano.bindTo("point", marker);
pano.setVisible(true);
});
I'm using this code:
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(41.640078, -102.669433),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mymap.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + point;
// comment *** streetview here ****
var marker = new google.maps.Marker({
map: map,
position: point
});
bindInfoWindow(marker, map, infoWindow, html);
}
});}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
Working example using DOM elements (rather than using string content):
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers used by the side_bar
var gmarkers = [];
// global "map" variable
var map = null;
var sv = new google.maps.StreetViewService();
var clickedMarker = null;
var panorama = null;
// Create the shared infowindow with three DIV placeholders
// One for a text string, oned for the html content from the xml, one for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var htmlContent = document.createElement("DIV");
content.appendChild(htmlContent);
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50),
content: content
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
zIndex: Math.round(latlng.lat() * -100000) << 5
});
marker.myHtml = html;
google.maps.event.addListener(marker, "click", function() {
clickedMarker = marker;
sv.getPanoramaByLocation(marker.getPosition(), 50, processSVData);
// openInfoWindow(marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length - 1) + ')">' + name + '<\/a><br>';
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var marker = clickedMarker;
openInfoWindow(clickedMarker);
if (!!panorama && !!panorama.setPano) {
panorama.setPano(data.location.pano);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
google.maps.event.addListener(marker, 'click', function() {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
});
}
} else {
openInfoWindow(clickedMarker);
title.innerHTML = clickedMarker.getTitle() + "<br>Street View data not found for this location";
htmlContent.innerHTML = clickedMarker.myHtml;
panorama.setVisible(false);
// alert("Street View data not found for this location.");
}
}
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data from example.xml
// downloadUrl("example.xml", function(doc) {
var xmlDoc = xmlParse(xmlData);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat, lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point, label, html);
bounds.extend(point);
}
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
// Zoom and center the map to fit the markers
map.fitBounds(bounds);
// });
}
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
var pin = new google.maps.MVCObject();
google.maps.event.addListenerOnce(infowindow, "domready", function() {
panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true
});
panorama.bindTo("position", pin);
});
// Set the infowindow content and display it on marker click.
// Use a 'pin' MVCObject as the order of the domready and marker click events is not garanteed.
function openInfoWindow(marker) {
title.innerHTML = marker.getTitle();
htmlContent.innerHTML = marker.myHtml;
pin.set("position", marker.getPosition());
infowindow.open(map, marker);
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm
google.maps.event.addDomListener(window, 'load', initialize);
var xmlData = '<markers> <marker lat="43.65654" lng="-79.90138" html="Some stuff to display in the<br>First Info Window" label="Marker One" /> <marker lat="43.91892" lng="-78.89231" html="Some stuff to display in the<br>Second Info Window" label="Marker Two" /> <marker lat="43.82589" lng="-79.10040" html="Some stuff to display in the<br>Third Info Window" label="Marker Three" /></markers> ';
/**
* Parses the given XML string and returns the parsed document in a
* DOM data structure. This function will return an empty DOM node if
* XML parsing is not supported in this browser.
* #param {string} str XML string.
* #return {Element|Document} DOM.
*/
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body {
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<!-- you can use tables or divs for the overall layout -->
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>

Make geocoding map zoom on scroll

I am looking at two different geocode examples I found and I am looking to get the best of both features. I have not had much experience with geocoding and I find the google docs hard to follow
This one does everything I want except scroll in when the user uses the mouse wheel. http://jsfiddle.net/Ep7Rr/
I would like this one if I could get the marker to move as the user drags the map like in the first one.http://jsfiddle.net/AjeTc/
I know there are different ways such as new GMap2 and new google.maps.Geocoder
The first one works with this code
<script>
function load() {
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(54.18173, -6.35284);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function(){
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function(){*/
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function() {*/
}); /*END GEvent.addListener(map, "moveend", function() {*/
} /*END if (GBrowserIsCompatible()){*/
} /*END function load*/
And the second uses this
<script type="text/javascript">
function showAddress() {
var map = new GMap2(document.getElementById("map"));
var address = document.getElementById('fullAddress').value;
return false;
} /*END function showAddress*/
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(54.18173, -6.35284);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Catch the event when the map is dragged.
Update the position of the marker by getting the map center
Geocode the position of the marker
google.maps.event.addListener(map, 'dragend', function() {
updateMarkerStatus('Drag ended');
marker.setPosition(map.getCenter());
geocodePosition(marker.getPosition());
});
like this : http://jsfiddle.net/ZYV9N/

Google maps v3 open infowindow on load

I using this technique: http://www.geocodezip.com/v3_MW_example_map2.html
I want to have the first info window open when the map loads.
I also want to be able to center the map when you click a location link.
Can anyone help?
JS:
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
var map = null;
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(50.822096, -0.375736),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Add markers to the map
// Set up three markers with info windows
// add the points
var point = new google.maps.LatLng(50.810438, -0.374925);
var center = new google.maps.LatLng(50.810438, -0.374925);
var marker = createMarker(point,"Worthing","<p><b>Worthing</b><br>1-13 Buckingham Road,<br>Worthing,<br>West Sussex,<br>BN11 1TH</p>")
var point = new google.maps.LatLng(51.497421,-0.141604);
var center = new google.maps.LatLng(51.497421,-0.141604);
var marker = createMarker(point,"London","<p><b>London</b><br>Portland House,<br>Bressenden Place,<br>London,<br>SW1E 5RS</p>")
var point = new google.maps.LatLng(-33.867487,151.20699);
var center = new google.maps.LatLng(-33.867487,151.20699);
var marker = createMarker(point,"Sydney","<p><b>Sydney</b><br>Level 1, Cosco House,<br>95-101 Sussex Street,<br>Sydney NSW<br>Australia 2000</p>")
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
$('#side_bar li:first-child').addClass("active");
$('#side_bar li').click(function(){
$('#side_bar li').removeClass("active");
$(this).addClass("active");
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var iconBase = '../Themes/FreshEgg/assets/img/';
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,
icon: iconBase + 'map_marker_24x46.png',
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
infowindow.setContent(contentString);
infowindow.open(map,marker);
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<li><a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a></li>';
}
google.maps.event.addDomListener(window, 'load', initialize);
HTML:
<ul class="list-inline" id="side_bar"></ul>
<div id="map_canvas"></div>
Add a 4th parameter to your createMarker() function for the default state of markers - createMarker(latlng, name, html, show) - where show will be a boolean variable: true to open on load, false to leave it closed. Then when you call createMarker() in your initialize() method specify true for the marker you want open on load.
Then in createMarker() add a condition that handles this for you - something like:
if (show) {
google.maps.event.trigger(marker, "click");
/*if you're going to take this approach, make sure this is triggered after
*you specify your listener
*alternately, you can also setContent() and open() your infoWindow here
*/
}
To have the map pan to the center when you click on the marker, you first need to disable the auto panning of the map when an infoWindow is open. This can be done where you set the options for your infoWindow:
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
disableAutoPan : true
});
Then, in your listener for the click event on the marker add the function to panTo(LatLng) the position of the marker on your map.
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
map.panTo(marker.getPosition());
});