google maps onclick go to marker on map - google-maps

I'm having issues trying to get my map to go to the marker of a location when a "View on Map" link is clicked. I keep getting the error "TypeError: map.setOptions is not a function".
Here's the code:
var infowindow = null;
function initialize(){
var myOptions = {
zoom:3,
center:new google.maps.LatLng(0,0),
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(
document.getElementById('map'),myOptions);
setMarkers(map,sites);
}
var infowindow = new google.maps.InfoWindow({
content:'Loading...'
});
var sites = [
['GIC Campers Sydney',-33.935477,151.012108,1,'xxx'],
['GIC Campers Brisbane',-27.5445735,153.0139405,1,'yyy'],
['GIC Campers Melbourne',-37.650735,144.940551,1,'zzz']
];
function setMarkers(map,markers){
var bounds = new google.maps.LatLngBounds();
var image = new google.maps.MarkerImage('/templates/home/images/google-pin.png',
new google.maps.Size(60,60),
new google.maps.Point(0,0),
new google.maps.Point(30,60));
for(var i=0;i<markers.length;i++){
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1],sites[2]);
var marker = new google.maps.Marker({
position:siteLatLng,
map:map,
icon:image,
title:sites[0],
zIndex:sites[3],
html:sites[4]
});
google.maps.event.addListener(marker,'click',function(){
map.setZoom(15);
map.setCenter(marker.getPosition());
infowindow.setContent(this.html);
infowindow.open(map,this);
});
bounds.extend(siteLatLng);
map.fitBounds(bounds);
}
};
function loadcity(which){
initialize();
if(which == 'gic-campers-sydney'){
var newPos = new google.maps.LatLng(-33.935477,151.012108);
map.setOptions({center:newPos,zoom:15});
}
if(which == 'gic-campers-brisbane'){
var newPos = new google.maps.LatLng(-27.5445735,153.0139405);
map.setOptions({center:newPos,zoom:15});
}
if(which == 'gic-campers-melbourne'){
var newPos = new google.maps.LatLng(-37.650735,144.940551);
map.setOptions({center:newPos,zoom:15});
}
}
jQuery(document).ready(function(e) {
initialize();
jQuery('.updatemap').click(function(e){
e.preventDefault();
});
});
and an example link:
<a onclick="loadcity('gic-campers-brisbane');" class="updatemap" href="#gic-campers-brisbane">View on map</a>
Any help on this would be greatly appreciated.

Your map variable is local to the initialize function. It is not available inside the loadcity function.
One fix is to make it global (like your infowindow):
var infowindow = null;
var map = null;
function initialize(){
var myOptions = {
zoom:3,
center:new google.maps.LatLng(0,0),
mapTypeId:google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(
document.getElementById('map'),myOptions);
setMarkers(map,sites);
}
Not sure why you recreate the map (call initialize() every time loadcity runs), you really should only need to do that once.

Related

Difficulty Adding Transit Layer to Google Maps

I am trying to add the Transit Layer to an existing map that came with my wordpress theme. I'm not sure if I'm doing it wrong but the map stops loading whenever I add the code that I found here (https://developers.google.com/maps/documentation/javascript/trafficlayer#transit_layer)
I know the file I need to edit is located in js/google_js/google_map_js and it looks like this......
/*global google */
/*global Modernizr */
/*global InfoBox */
/*global googlecode_regular_vars*/
var gmarkers = [];
var current_place=0;
var actions=[];
var categories=[];
var vertical_pan=-190;
var map_open=0;
var vertical_off=150;
var pins='';
var markers='';
var infoBox = null;
var category=null;
var width_browser=null;
var infobox_width=null;
var wraper_height=null;
var info_image=null;
var map;
var found_id;
var selected_id = '';
var javamap;
var oms;
function initialize(){
"use strict";
var mapOptions = {
flat:false,
noClear:false,
zoom: parseInt(googlecode_regular_vars.page_custom_zoom),
scrollwheel: false,
draggable: true,
center: new google.maps.LatLng(googlecode_regular_vars.general_latitude, googlecode_regular_vars.general_longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl:false,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP]
},
disableDefaultUI: true
};
if( document.getElementById('googleMap') ){
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
}else{
return;
}
google.maps.visualRefresh = true;
if(mapfunctions_vars.show_g_search_status==='yes'){
set_google_search(map)
}
if(mapfunctions_vars.map_style !==''){
var styles = JSON.parse ( mapfunctions_vars.map_style );
map.setOptions({styles: styles});
}
google.maps.event.addListener(map, 'tilesloaded', function() {
jQuery('#gmap-loading').remove();
});
if (Modernizr.mq('only all and (max-width: 1025px)')) {
map.setOptions({'draggable': false});
}
if(googlecode_regular_vars.generated_pins==='0'){
pins=googlecode_regular_vars.markers;
markers = jQuery.parseJSON(pins);
}else{
if( typeof( googlecode_regular_vars2) !== 'undefined' && googlecode_regular_vars2.markers2.length > 2){
pins=googlecode_regular_vars2.markers2;
markers = jQuery.parseJSON(pins);
}
}
if (markers.length>0){
setMarkers(map, markers);
}
if(googlecode_regular_vars.idx_status==='1'){
placeidx(map,markers);
}
//set map cluster
map_cluster();
/*function scrollwhel(event){
if(map.scrollwheel===true){
event.stopPropagation();
}
}
google.maps.event.addDomListener(document.getElementById('googleMap'), 'mousewheel', scrollwhel);
google.maps.event.addDomListener(document.getElementById('googleMap'), 'DOMMouseScroll', scrollwhel);
*/
oms = new OverlappingMarkerSpiderfier(map, {markersWontMove: true, markersWontHide: true,keepSpiderfied :true,legWeight:3});
setOms(gmarkers);
}
///////////////////////////////// end initialize
///////////////////////////////////////////////////////////////////////////////////
if (typeof google === 'object' && typeof google.maps === 'object') {
google.maps.event.addDomListener(window, 'load', initialize);
}
I know that the code that I need to enter is this....
function initialize() {
var myLatlng = new google.maps.LatLng(51.501904,-0.115871);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help at all would be greatly appreciated. Thank you.
I think you should add the TransitLayer code:
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
under the map object generation code:
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
Then it should work.
working fiddle

Can someone tell me why I can see an InfoWindow when I click on an map marker?

Here is my code that will pull data from mysql and display the markers on the map. But I cant get the info windows to show when I click on a marker. Thank for any help.
The reference to the infowindows is at the very bottom on the page close to the end of the code after the ajax reference.
Thanks
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function LoadMarkers(encodedString)
{
var bounds = new google.maps.LatLngBounds();
var stringArray = [];
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
info.open(map,this);
infos[0]=info;
});
bounds.extend(lat);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
map.fitBounds(bounds);
}
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = null;//new google.maps.Map(document.getElementById("map_canvas"), myOptions);
jQuery(document).ready( function($){
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
LoadMarkers(document.getElementById("encodedString").value);
setInterval(function () {
jQuery.ajax({
url:'ajaxload.php',
type: "POST",
data: {'refreshed':true},
success: function(data)
{
LoadMarkers(data);
}
});
}, 10000);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
The function LoadMarkers is defined in global scope, but the function closeInfos is defined locally inside the $.ready-callback.
Because of that the call of closeInfos() inside the click-handler of the marker fails and stops the further execution of the click-handler.
You must make closeInfos global accessible:
window.closeInfos=function(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}

Change Google maps to re-use single infowindow rather than creating multiple

I have an increasingly complex Google map which plots thousands of points and clusters them. I have an infowindow opening when the user clicks one of the map markers and it all works great. However, one improvement I'd like to make is to force all other infowindows to close when a new one is opened so that only 1 infowindow can be open at once.
I've tried adding some code (if (infowindow) infowindow.close();) into the listener function to do this, but I think the issue is wider in that I'm currently creating an infowindow for each marker, and there is no access to other infowindows on the event which opens a new one. So, from reading around this it would seem to be a better idea to have just one infowindow which gets reused rather than many.
Trouble is, the code is at the edge of what I can really understand, and my experiments in doing this so far have just broken everything.
The code I currently have is as follows:
var _iconCenter = new google.maps.MarkerImage('/css/img/map-marker.png',
new google.maps.Size(38, 48),
new google.maps.Point(0,0),
new google.maps.Point(19, 44));
var shadow = new google.maps.MarkerImage('/css/img/map-marker-shadow.png',
new google.maps.Size(57, 49),
new google.maps.Point(0,0),
new google.maps.Point(7, 44));
var _icon = '/css/img/map-marker-purple.png';
var infowindow;
var markersArray = [];
var map;
var currentPosition = 0;
var currentmarker;
var firstload = true;
var maploaded = false;
var interval = 5000;
var geocoder;
var stylez = [];
function initialize(items,loop,zoom) {
geocoder = new google.maps.Geocoder();
if (items.length > 0) {
var latlng = new google.maps.LatLng(items[0].Lat, items[0].Lng);
var myOptions = {
zoom: zoom,
center: latlng,
//mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setOptions({styles: stylez});
for (var i = 0; i < items.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(items[i].Lat, items[i].Lng),
title: items[i].Title,
icon: _icon,
shadow: shadow,
infocontent: items[i].Description
});
marker.setMap(map);
attachListener(marker,'marker:'+i);
markersArray.push(marker);
}
//set style options for marker clusters (these are the default styles)
mcOptions = {
gridSize: 44
}
var markerCluster = new MarkerClusterer(map, markersArray, mcOptions);
google.maps.event.addListener(map, "tilesloaded", function () {
if(loop == true){
SetLoop();
}
});
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
var infowindow = new google.maps.InfoWindow();
map.setCenter(new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng()));
infowindow.setContent(content);
infowindow.open(map,this);
});
}
}
}
function SetLoop() {
//This will fire everytime map loads or recenteres
maploaded = true;
if (firstload) {
firstload = false;
Recenter();
}
}
function Recenter() {
//If previous iteration is not loaded completely, wait to avoid errors
//It could happen for slow internet connection
if (maploaded) {
maploaded = false;
} else {
//keep adding 1 second to interval for slow connection till page loads
interval = interval + 1;
setTimeout("Recenter()", interval);
return;
}
if (infowindow != null && currentmarker != null) {
//currentmarker.icon = _icon;
currentmarker.icon = _iconCenter;
currentmarker.setMap(map);
infowindow.close(map, currentmarker);
}
markersArray[currentPosition].icon = _iconCenter;
markersArray[currentPosition].setMap(map);
map.setCenter(new google.maps.LatLng(markersArray[currentPosition].getPosition().lat(), markersArray[currentPosition].getPosition().lng()));
infowindow = new google.maps.InfoWindow({
content: markersArray[currentPosition].infocontent,
size: new google.maps.Size(50, 50)
});
infowindow.open(map, markersArray[currentPosition]);
currentmarker = markersArray[currentPosition];
if (currentPosition >= markersArray.length - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
if (markersArray.length > 1) {
setTimeout("Recenter()", interval);
}
}
Is the best way to re-use the infowindow or is it okay to do this another way? Any help in pointing me in the right direction here would be much appreciated, thanks folks!
Remove the 'var infowindow' declaration from function attachListener(). If you declare it inside the function it becomes local to the function and you create a new instance each time you execute the function. so:
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
// marker.getPosition() already returns a google.maps.LatLng() object
map.setCenter(marker.getPosition());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map,this);
});
}
and instead, declare it as a global variable:
var _icon = '/css/img/map-marker-purple.png';
var infowindow = new google.maps.InfoWindow();
//...etc
so that you have only one infowindow object in the whole application

Google Maps API v3 - Arrays and InfoWindows

I'm been trying to make an infowindow for each of my markers for a while now but cant get it to work.
This is what I came up with:
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
content: nazwa
}));
google.maps.event.addListener(marker, 'click', function() {
var info = new google.maps.InfoWindow({content: this.content});
});
}
And the full code is:
<script type="text/javascript">
var map;
var marker1;
var markert = [];
var lati;
var loni;
var infowindow;
I start the map:
function initialize() {
lat = 50.42952;
long = 15.60059;
var latlng = new google.maps.LatLng(lat, long);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggableCursor:'crosshair',
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
dymek = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function(event) {
add_marker(event.latLng, 'Your new marker', 'Your new marker' );
});
}
This function gets the address of the clicked point:
function findAddress(event) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: event.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
infoWindow.setContent(results[0].formatted_address);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
}
});
}
This function adds a new marker on the map where I clicked:
function add_marker( pos, pos_title, pos_str ) {
marker1 = new google.maps.Marker( {
position: pos,
map: map,
draggable: true,
title: pos_title
});
map.setZoom(15);
map.setCenter(marker1.getPosition());
LoadMarkers();
}
This function loads the nearby points that are near the marker I created in the function above:
function LoadMarkers()
{
var adres='add.xml?lat='+lati+'&long='+loni;
jx.load(adres, function(xml)
{
var markery = xml.getElementsByTagName("marker");
for(var i=0; i<markery.length; i++)
{
var latt = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var nazwa = markery[i].attributes.getNamedItem("nazwa").nodeValue;
var markert = addMarkers(latt,lon,ikona_url,nazwa);
}
},'xml','get');
}
This function actually ads the nearby markers on the map. These markers are the ones that I want the infowindow to show:
function addMarkers(latt,lon,ikona_url,nazwa)
{
var rozmiar = new google.maps.Size(30,23);
var punkt_startowy = new google.maps.Point(0,0);
var punkt_zaczepienia = new google.maps.Point(15,12);
var ikona = new google.maps.MarkerImage(ikona_url, rozmiar, punkt_startowy, punkt_zaczepienia);
markert.push(new google.maps.Marker({
position: new google.maps.LatLng(latt,lon),
title: nazwa,
icon: ikona,
map: map,
animation: google.maps.Animation.DROP }));
google.maps.event.addListener(markert, 'tilesloaded', function() {
var info = new google.maps.InfoWindow({content: nazwa});
});
}
You're not actually opening the infowindow at any point. Please review this documentation and example, and adapt your code accordingly. You actually need to use the open method for infowindow.

How to get the Google Map based on Latitude on Longitude?

I want to display Google map in my web page based on longitude and latitude. First user want to enter longitude and latitude in two text box's. Then click submit button I have to display appropriate location in Google map.And also I want to show the weather report on it.How to do that? Thank You.
Create a URI like this one:
https://maps.google.com/?q=[lat],[long]
For example:
https://maps.google.com/?q=-37.866963,144.980615
or, if you are using the javascript API
map.setCenter(new GLatLng(0,0))
This, and other helpful info comes from here:
https://developers.google.com/maps/documentation/javascript/reference/?csw=1#Map
this is the javascript to display google map by passing your longitude and latitude.
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
Have you gone through google's geocoding api. The following link shall help you get started:
http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
Firstly add a div with id.
<div id="my_map_add" style="width:100%;height:300px;"></div>
<script type="text/javascript">
function my_map_add() {
var myMapCenter = new google.maps.LatLng(28.5383866, 77.34916609);
var myMapProp = {center:myMapCenter, zoom:12, scrollwheel:false, draggable:false, mapTypeId:google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("my_map_add"),myMapProp);
var marker = new google.maps.Marker({position:myMapCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_key&callback=my_map_add"></script>
<script>
function initMap() {
//echo hiii;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(8.5241, 76.9366),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('package');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
// var name = markerElem.getAttribute('name');
// var address = markerElem.getAttribute('address');
// var type = markerElem.getAttribute('type');
// var latitude = results[0].geometry.location.lat();
// var longitude = results[0].geometry.location.lng();
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('latitude')),
parseFloat(markerElem.getAttribute('longitude'))
);
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var package = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
package.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, package);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}