Change icon of marker clicked when you have multiple markers - javascript

I am trying to change the marker icon when the marker is clicked the problem is the code below only changes the last marker I added to the map not the marker I am clicking on, so if I only had one marker it would work fine. I tried looking it up but all the examples I could find only work with 1 marker loaded in the map. I tried the listener two different ways the second one is commented out below the the first way and both just change the icon of the the last marker loaded.
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 95%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 95%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://unpkg.com/#google/markerclustererplus#4.0.1/dist/markerclustererplus.min.js"></script>
<script>
let markers = [];
let map;
function loadMarkers(ssStr)
{
$.getJSON(ssStr, function(data) {
for (var i = 0; i < data.feed.entry.length; i++)
{
var latLng = new google.maps.LatLng(data.feed.entry[i]['gsx$lat']['$t'],
data.feed.entry[i]['gsx$long']['$t']);
var marker = new google.maps.Marker({
position: latLng,
map: map,
label:data.feed.entry[i]['gsx$structure']['$t'],
icon: { url: "http://maps.google.com/mapfiles/ms/icons/red.png" }
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
//Change the marker icon
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
});
/* marker.addListener("click", (event) => {
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green.png');
}); */
}
var latLng = new google.maps.LatLng(data.feed.entry[0]['gsx$lat']['$t'],
data.feed.entry[0]['gsx$long']['$t']);
map.setCenter(latLng);
});
}
function initMap() {
console.log("initMap");
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(41.5, -72)
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadMarkers("http://spreadsheets.google.com/feeds/list/SSID/od6/public/values?alt=json");
}
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Related

Javascript GoogleMaps API Animation Onclick for Array of points

I've searched the web but can't seem to locate an answer for my issue. I believe I'm close but just can't get this to work as intended.
I'd like to plot an array of locations on a google map and start with the DROP animation, then when a user clicks a point, I'd like it to bounce.
My current code does 1/2 the job, however, when you click it's targeting the last value in my array. The BOUNCE animation works but it doesn't seem to be applied to all values in my array. Can you point at what I'm missing in the code?
Thanks for all the help!
<html>
<head>
<!-- styles put here, but you can include a CSS file and reference it instead! -->
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script type="text/javascript">
// Create a map variable
var map;
var markers = [];
// Function to initialize the map within the map div
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.74135, lng: -73.99802},
zoom: 10
});
// Create a single latLng literal object.
var locations = [
{title: 'Beer', location: new google.maps.LatLng(47.666633, -122.371453)},
{title: 'Home', location: new google.maps.LatLng(47.613141, -122.320587)},
{title: 'Work', location: new google.maps.LatLng(47.624812, -122.315134)}
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var position = locations[i].location;
var title = locations[i].title;
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
animation: google.maps.Animation.DROP,
id: i
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', function(){
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
});
// markers.push(marker);
}
map.fitBounds(bounds);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=&v=3&callback=initMap">
</script>
</body>
</html>
One option would be to use this inside the click event listener function to reference the clicked marker.
google.maps.event.addListener(marker, 'click', function(){
if (this.getAnimation() !== null) {
this.setAnimation(null);
} else {
this.setAnimation(google.maps.Animation.BOUNCE);
}
});
(you can also use function closure)

How to highlight map marker upon selection of an html element

Need help with getting html elements interact with google maps.
I have 2 sections on a Web page. On the right side of the page, I have a map showing multiple markers. On the left side of the page, I have a list with addresses which correspond to the markers in the map.
Please suggest pointers on how to highlight a marker when the corresponding address is selected from the list on the left side of the page.
Okay, I made it with hover() . Hovering over the div highlights the marker
<head>
<style>
html, body, #map-canvas {
height: 400px;
margin: 0px;
padding: 0px
}
#markers_info .marker {
height: 40px;
cursor: pointer;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?"></script>
<script>
/**
jQuery events
*/
$(document).ready(function() {
// initiate Google maps
initialize();
// make a .hover event
$('#markers_info .marker').hover(
// mouse in
function () {
// first we need to know which <div class="marker"></div> we hovered
var index = $('#markers_info .marker').index(this);
markers[index].setIcon(highlightedIcon());
},
// mouse out
function () {
// first we need to know which <div class="marker"></div> we hovered
var index = $('#markers_info .marker').index(this);
markers[index].setIcon(normalIcon());
}
);
});
/**
Google Maps stuff
*/
var markerData = [ // the order of these markers must be the same as the <div class="marker"></div> elements
{lat: 50.84498605, lng: 4.349977747, title: 'Manneken Pis'},
{lat: 50.84848913, lng: 4.354053363, title: 'Jeanneke Pis'},
{lat: 50.84673465, lng: 4.352466166, title: 'Grand Place'}
];
var map;
var markers = [];
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(50.84673465,4.352466166), // Brussels, Belgium
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (var i=0; i<markerData.length; i++) {
markers.push(
new google.maps.Marker({
position: new google.maps.LatLng(markerData[i].lat, markerData[i].lng),
title: markerData[i].title,
map: map,
icon: normalIcon()
})
);
}
}
// functions that return icons. Make or find your own markers.
function normalIcon() {
return {
url: 'http://1.bp.blogspot.com/_GZzKwf6g1o8/S6xwK6CSghI/AAAAAAAAA98/_iA3r4Ehclk/s1600/marker-green.png'
};
}
function highlightedIcon() {
return {
url: 'http://steeplemedia.com/images/markers/markerGreen.png'
};
}
//google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="markers_info">
<div class="marker">Manneken Pis, 50.84498605,4.349977747</div>
<div class="marker">Jeanneke Pis, 50.84848913,4.354053363</div>
<div class="marker">Grand Place, 50.84673465,4.352466166</div>
</div>
</body>

Google maps infowindow display kml object name and link

I have some working code to display a KML layer on Google maps. When you click on the various parts of the layer their respective name pops up in an info window.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
// Load Google Maps API
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXX&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(51.875696, -0.624207);
var mapOptions = {
zoom: 6,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var kmlLayer = new google.maps.KmlLayer({
url: 'http://XXXXXXX.org/gliding/grid3.kml',
suppressInfoWindows: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width:100%; height:100%; float:left"></div>
</body>
</html>
I would like the info window to also contain a link to a page with the same name as object clicked on. For example if the user clicks on a shape in the KML layer called Tom the info window says Tom Click Here. If the user clicks the link they are taken to www.XYZ.com/Tom.
I'm sure this is quite simple, but I'm new to javascript and can't get it to work.
This is more a hack than a solution (which means google could change a property name and this would stop working.
However, here you go
google.maps.event.addListener(kmlLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += 'Click Here';
showInContentWindow(text);
});

Google maps API JS3 SSL

I have a website here : www.hosting6280514.az.pl/ that uses SSL ... I try to display google maps on that page, but only the controls, markers and map/satellite switch is displayed, the actual map isn't. This is the code I'm using:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function refreshing() {
setTimeout("location.reload(true);",5000);
}
function initialize()
{
var position = new google.maps.LatLng(<?php echo$lat; ?>,<?php echo$lgt; ?>);
var mapOptions =
{
zoom: 18,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
/*var image = new google.maps.MarkerImage('http://hosting6280514.az.pl/pawel/images/car.png',
// This marker is 129 pixels wide by 42 pixels tall.
new google.maps.Size(129, 42),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 18,42.
new google.maps.Point(18, 42)
);*/
var marker = new google.maps.Marker(
{
position: position, // its position is where position variable points
title: "Car's position"
//icon: image
});
marker.setMap(map); // To add the marker to the map, call setMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="JavaScript:refreshing();">
<div id="map-canvas"></div>
</body>
</html>
Sorry, Question is: does anyone know why map is not displaying ?
In order to update the position on the map, try something along those lines.
You may also use geolocation.watchPosition if you would like to get the current position.
var position, marker;
function updateLocation() {
$.ajax({
url: '/something.php',
dataType: 'JSON',
success: function(data) {
position = new google.maps.LatLng(data.lat, data.lng);
marker.setPosition(position);
}
});
}
function initialize() {
position = // same as you have it
// ...
marker = // same as you have it
}

Retrieve marker position to fields to submit

I have this code from the Google API docs. It does exactly what I want except i need to be able to get to get latitude and longitude of the marker once its been placed.
In my site , i have enabled the option to be able to select a location on the map, but i need to somehow get the latitude and longitude information from the marker that the customer has set, specifically in hidden fields so that i could store them when data is posted $_POST.
The code I have now is:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=jsdlkajslkdjaslkdja&sensor=false&language=ar&region=SAU">
</script>
<script type="text/javascript">
var map;
var markersArray = [];
function initialize() {
var haightAshbury = new google.maps.LatLng(26.1631, 50.2044188);
var mapOptions = {
zoom: 7,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
// Shows any overlays currently in the array
function showOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
I mainly need help on the JS side of this.
There is a markersArray-variable which contains all markers.
Loop over the array, you will get the lat/lng for each item by using
item.getPosition().lat() and item.getPosition().lng()
<edit>
Limiting to 1 marker is easy.
Change this line:
google.maps.event.addListener(map, 'click', function(event) {
into this:
google.maps.event.addListenerOnce(map, 'click', function(event) {
</edit>

Categories

Resources