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.
Related
I have literally been trying anything and everything, but the map displays somewhere in Antarctica, when the coordinates that I am receiving, are for cities in the US.
The following is the code that inits the map:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
console.log(fastestCitiesApi);
var tempLatLng = fastestCitiesApi[0]['latLng'];
console.log(tempLatLng);
var latLng = tempLatLng.split(',');
console.log('latLng[0]: ' + latLng[0]);
console.log('latLng[1]: ' + latLng[1]);
const myLatLng = new google.maps.LatLng({ lat: parseFloat(latLng[0]), lng: parseFloat(latLng[1]) });
const mapOptions = {
zoom: 4,
center: myLatLng
};
const map = new google.maps.Map(document.getElementById('fastest_cities_map'), mapOptions);
new google.maps.Marker({
position: myLatLng,
map,
title: 'somewhere',
});
}
initTest();
});
As you can see by the following screen shot of the console is showing, that the coordinates are 36, 78 - which when I do a look up on google for Boydton, VA - those are the coordinates that is returned - link to google search for Boydton, VA lat long
As you can see by the screen shot, I have zero errors. What am I doing wrong?
Thanks in advance
Thanks to #Gray pointing out that the long should be negative, the rest of the array loaded up the markers as expected.
Here's the final code:
$(window).on('load', function() {
// eslint-disable-next-line
function initTest() {
/* init vars */
const map = new google.maps.Map(document.getElementById('fastest_cities_map'));
var fastestCitiesApi = JSON.parse(document.getElementById('fastestCitiesApi').value);
// console.log(fastestCitiesApi);
var tempLatLng = '';
var latLng = [];
var markerOptionsArray = new Array();
var latlngArray = new Array();
var myLat = new Array();
var myLng = new Array();
var markers = [];
var nameArray = [];
var infowindow = new google.maps.InfoWindow({maxWidth: 350});
/* create arrays for markers */
for(var item in fastestCitiesApi) {
tempLatLng = fastestCitiesApi[item]['latLng'];
nameArray.push(fastestCitiesApi[item]['city']);
// console.log(tempLatLng);
latLng = tempLatLng.split(',');
myLat.push(latLng[0]);
myLng.push(latLng[1]);
// console.log('latLng[0]: ' + latLng[0]);
// console.log('latLng[1]: ' + latLng[1]);
markers.push({
lat: myLat[item],
lng: myLng[item],
name: nameArray[item],
});
}
// console.log('markers: ' + JSON.stringify(markers));
var bounds = new google.maps.LatLngBounds();
for (var v=0; v<markers.length; v++)
{
var secheltLoc = new google.maps.LatLng(markers[v].lat, markers[v].lng);
var myOptions = {
content: markers[v].name
,boxStyle: {
border: "none"
,textAlign: "center"
,fontSize: "12pt"
,width: "120px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-50, 0)
,position: secheltLoc
,closeBoxURL: ""
,isHidden: false
,pane: "mapPane"
,enableEventPropagation: true
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[v].lat, markers[v].lng),
map: map,
center: new google.maps.LatLng(markers[v].lat, markers[v].lng)
});
google.maps.event.addListener(marker, 'click', (function (marker, v) {
return function () {
infowindow.setContent(markers[v].name);
infowindow.open(map, marker);
}
})(marker, v));
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
marker.open = false;
});
bounds.extend(new google.maps.LatLng(markers[v].lat, markers[v].lng));
myLatLng = markers[v].lat+','+markers[v].lng;
}
map.fitBounds(bounds);
}
// alert(google.maps.Map);
initTest();
});
The following is a screen shot of the result of the eight city array:
I'm trying to place a marker on click in google maps along with populating input boxes with the lat and lng. I need the code to clear all the existing markers first before placing the new marker and updating the lat and lng. everything works except when I add code to try clear all the markers.
The below code works perfectly but does not clear the old markers before placing the new one.
Thank you.
Working code without clearing existing markers...
<div id="map"></div>
<script>
var map;
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
</script>
Not working code with clearing markers before adding a new one...
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker = new google.maps.Marker({
map: map,
draggable: false
});
clearOverlays();
marker.setPosition(marker_position);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
Thank you.
seem you have placed the code in the wrong place .. try
<div id="map"></div>
<script>
var map;
var markersArray = [];
function initMap() {
var latlng = new google.maps.LatLng(-29, 25);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: latlng,
});
clearOverlays();
marker = new google.maps.Marker({
map: map,
draggable: false
});
google.maps.event.addListener(marker,"click",function(event){});
google.maps.event.addListener(map, 'click', function(event){
var marker_position = event.latLng;
marker.setPosition(marker_position);
markersArray.push(marker);
document.getElementById("latFld").value = event.latLng.lat();
document.getElementById("lngFld").value = event.latLng.lng();
})
}
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray = [];
}
</script>
I have create Map that shows several markers with info window. The goal is to have the info window to close upon clicking on a different one, but that is not happening. I am not sure why. Any help is appreciated. thank you
(document).ready(function(){
//GLOBAL VARIABLE
var jobsListings='';
var mapOptions;
var lng='';
var lat='';
var infowindow;
var Outerarray = [];
$('#SearchJobs').click(function(){
$("#JobsListingRender").html('<img src="images/preloader.gif" width=40>Searching for jobs. please wait....');
var htmldiv='';
var ZipCode = $('#ZipCode').val();
var lng='';
var lat='';
$.ajax({
datatype:"json",
url: "https://maps.googleapis.com/maps/api/geocode/json?address="+ZipCode,
async:false,
success:
function(data){
lng= data.results[0].geometry.location.lng;
lat= data.results[0].geometry.location.lat;
//var map = new google.maps.Map(document.getElementById('map-canvas'),
// mapOptions);
//setMarkers(map,zip,l);
}
})
var bounds = new google.maps.LatLngBounds();
$.get("proxy.php?Zip="+ZipCode, function(data, status){
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var data = jQuery.parseJSON(data);
//console.log(jobsListings.Results);
MarkersArray= [];
$.each(data.results, function(i, val) {
//var myLatLng = new google.maps.LatLng(Outerarray[i][1],Outerarray[i][2]);
if(typeof val.Company !=='object')
{
htmldiv +="<div><strong>Company Name:</strong>"+val.company+"</div>";
htmldiv +="<div><strong>Title:</strong>"+val.jobtitle+"</div>";
htmldiv +="<div><strong>City:</strong>"+val.city+"</div>";
htmldiv +="<div><strong>Location:</strong>"+val.formattedLocation+"</div>";
htmldiv +="<div><strong>Pay:</strong>"+val.Pay+"</div>";
htmldiv +="<button class='btn btn-primary'>Details</button>";
htmldiv +="<button class='btn btn-info pull-right'>Apply on Site</button>";
htmldiv +="<hr>";
}
MarkersArray= new Array();
MarkersArray[0] = val.latitude;
MarkersArray[1] = val.longitude;
MarkersArray[2] = val.company; //company name
MarkersArray[3] = i; //index
MarkersArray[4] = val.jobtitle; //jobtitle
MarkersArray[5] = val.formattedLocation; //location
MarkersArray[6] = val.city; //location
Outerarray.push(MarkersArray);
});
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (x = 0; x < Outerarray.length; x++) {
var marker, i;
var infow='';
infow ="<div><strong>Company Name:</strong>"+Outerarray[x][2]+"</div>";
infow +="<div><strong>Title:</strong>"+Outerarray[x][4]+"</div>";
infow +="<div><strong>City:</strong>"+Outerarray[x][6]+"</div>";
infow +="<div><strong>Location:</strong>"+Outerarray[x][5]+"</div>";
infow +="<button class='btn btn-primary'>Details</button>";
infowindow = new google.maps.InfoWindow({
content:infow
});
console.log(Outerarray[x]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(Outerarray[x][0], Outerarray[x][1], Outerarray[x][3]),
map: map,
icon:"images/eye_icon_blue.png",
id:x
});
//bindInfoWindow(marker, map, infowindow, infow);
bindInfoWindow(marker, map, infowindow, infow,i)
}
function bindInfoWindow(marker, map, infowindow, description) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {
infowindow.close();
}
infowindow.setContent(description);
infowindow.open(map, marker);
});
}
$("#JobsListingRender").html('');
$("#JobsListingRender").html(htmldiv);
});
});
})
i solved by cresting a local variable iWindow:
function bindInfoWindow(marker, map, description) {
iWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
if (iWindow) {
iWindow.close();
}
iWindow.setContent(description);
iWindow.open(map, marker);
});
}
I am displaying markers on a Google map .
When i click on the marker , i am setting it to different color (blue)
like this
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
This is my full code
var map;
var global_markers = [];
var markers = [[37.09024, -95.712891, 'trialhead0'], [-14.235004, -51.92528, 'trialhead1'], [-38.416097, -63.616672, 'trialhead2']];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker();
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
http://jsfiddle.net/ZLuTg/1008/
My question is that when i click on another Marker , how can i set the prevous marker which is in blue color to its original color
You already have an array of all your markers. Loop over them, resetting their icons.
Either do this for all the markers, then set the current one to blue. Or within the loop have an if statement checking if the one being looped over is the currently clicked one (I prefer the first option).
google.maps.event.addListener(global_markers[i], 'click', function() {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon("http://maps.google.com/mapfiles/ms/icons/red-dot.png");
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
Your original marker is the default marker. To set it back to that call setIcon(null).
google.maps.event.addListener(global_markers[i], 'click', function () {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon(null);
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
working fiddle
code snippet:
var map;
var global_markers = [];
var markers = [
[37.09024, -95.712891, 'trialhead0'],
[-14.235004, -51.92528, 'trialhead1'],
[-38.416097, -63.616672, 'trialhead2']
];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker();
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
for (var j = 0; j < global_markers.length; j++) {
global_markers[j].setIcon(null);
}
this.setIcon("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
#map_canvas {
width: 600px;
height: 500px;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas"></div>
i've implemented google maps v3, it updates while bounds_changed event but the problem is when the event triggers it renders the markers more than once, any suggestions.
i've added the makers to marker manager.
var map = null;
var myLatLng = null;
var sidebarHtml = "";
var infowindow = infowindow = new google.maps.InfoWindow({});;
var mgr = null;
var currentBounds = null;
var xml = null;
var markers = null;
var markersArray = [];
var customIcons = {
restaurant: {
icon: 'images/icon_01.png'
},
bar: {
icon: 'images/icon_02.png'
}
}
function load() {
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
mgr = new MarkerManager(map, {fitBounds: true});
google.maps.event.addListener(map, 'bounds_changed', downloadUrl);
}
function downloadUrl() {
var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest;
var params = "";
var url = "phpmysqlajax_genxml.php";
request.onreadystatechange = function() {
if(request.readyState == 4) {
//alert(request.responseXML);
useTheData(request);
}
};
request.open("GET", url + params, true);
request.send(null);
}
function useTheData(data) {
currentBounds = map.getBounds();
xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
mgr.clearMarkers();
if (!currentBounds) currentBounds = new google.maps.LatLngBounds();
sidebarHtml = '<ul class="sidebar">';
for(var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var type = markers[i].getAttribute("type");
var latlng = new google.maps.LatLng(lat, lng);
if (currentBounds.contains(latlng)) {
attachMarker( name, address, latlng, type );
markerSidebarEntry(i);
}
}
sidebarHtml += "</ul>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
function attachMarker( name, address, latlng, type ) {
var marker = new google.maps.Marker({
position : latlng,
map: map,
icon : customIcons[type].icon
});
mgr.addMarker(marker, 5);
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent( address );
infowindow.open(map, this);
});
// add marker here.
}
function markerSidebarEntry(i) {
var name = markers[i].getAttribute("name");
sidebarHtml += '<li class="' + markers[i].getAttribute("type") + '">' + name + '</li>';
}
function markerClick(i) {
google.maps.event.trigger(markersArray[i], "click");
}
It may just be a copy-paste error, but this code doesn't seem correct (double-declaration of 'infowindow' and duplicated ; at the end):
var infowindow = infowindow = new google.maps.InfoWindow({});;
Also here you don't need the () surrounding the {}
var myOptions = ({
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
Suggest you run your JS code through something like JSLint.