How to update coordinates of marker? - google-maps

I use Google Maps API and add the markers on the map:
for(var i = 1; i <= 100; i++){
var position = {lat : i, lng : i};
var marker = new google.maps.Marker({
position: position,
map: map,
draggable: true
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
How I can update coordinates for marker[i] = 22 if this marker was created before?

Pusth the markers in an array and use setPosition
var markers;
var k;
for(var i = 1; i <= 100; i++){
var position = {lat : i, lng : i};
var marker = new google.maps.Marker({
position: position,
map: map,
draggable: true
});
k = markers.push(marker);
markers[k-1].addListener('click', function() {
infowindow.open(map, this);
});
}
.....
var myNewlatlng = new google.maps.LatLng( 24.397, 40.644);
markers[22] setPosition(myNewlatlng);

Related

Google maps get position of an marker

I am adding multiple markers, and what I want to do is on click, get that specific marker position.
However at the moment it does work however it displays lat and lng for the last marker created. How can this be solved so that when I click on the marker it will give me that specific position of that marker.
function algolia_search(position) {
clearOverlays();
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'businesses';
var PARAMS = { hitsPerPage: 20 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
marker.addListener('click', function() {
var destinationLat = marker.getPosition().lat();
var destinationLng = marker.getPosition().lng();
console.log(lat);
console.log(lng);
console.log(destinationLat);
console.log(destinationLng);
you need a listerner on map for click in event.latLng you have coordinates
google.maps.event.addListener(map, 'click', function(event) {
alert ( 'Lat : ' + event.latLng.lat() + ' Lng : ' + event.latLng.lng())
});
do the fact you have already place the marker on maps you could use a closure
var addListenerOnPoint = function(actMark){
actMark.addListener('click', function() {
alert ( 'Lat : ' + actMark.position.lat() + ' Lng : ' +actMark.position.lng());
});
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
addListenerOnPoint(marker,
);
markers.push(marker);
}

Google maps v3 - Add markers at the center of tiles

function initialize() {
var myLatlng;
var mapOptions;
myLatlng = new google.maps.LatLng(29.98439980, -95.34140015);
mapOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
drawRectangle(map);
var result = {"regionList":[{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.34890747070312,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.980682373046875},{"centerLongitude":-95.33389282226562,"imageIcon":"../images/untested-icon.png","centerLatitude":29.988117218017578}]};
alert(result);
addMarkersAtRegionCenter(map, result);
});
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for(var i=0; i<length; i++)
{
var image = result.regionList[i].imageIcon;
//alert("Latitude : " + result.regionList[i].centerLatitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude,result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() {
window.location.href = marker.url;
}
})(marker, i));
}
}
function drawRectangle(map) {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var numberOfParts = 4;
var tileWidth = (northEast.lng() - southWest.lng()) / numberOfParts;
var tileHeight = (northEast.lat() - southWest.lat()) / numberOfParts;
for (var x = 0; x < numberOfParts; x++) {
for (var y = 0; y < numberOfParts; y++) {
var areaBounds = {
north: southWest.lat() + (tileHeight * (y+1)),
south: southWest.lat() + (tileHeight * y),
east: southWest.lng() + (tileWidth * (x+1)),
west: southWest.lng() + (tileWidth * x)
};
var area = new google.maps.Rectangle({
strokeColor: '#FF0000',
//strokeOpacity: 0.8,
strokeWeight: 2,
//fillColor: '#FF0000',
//fillOpacity: 0.35,
map: map,
bounds: areaBounds
});
}
}
}
}
google.maps.event.addDomListener(window, "load", initialize);
In the above code, I am trying to add markers at the center of each rectangle. But I am not able to add markers. I have hard coded image icon value since I don't have image mentioned in the array.
Thanks in advance for your help.
Related question: Google maps api v3 - divide region into equal parts using tiles
Simpler to add the markers to the centers of the rectangles when you create them:
var centerMark = new google.maps.Marker({
position: area.getBounds().getCenter(),
map: map
});
proof of concept fiddle
To add the markers from the response to the map (the positions in the posted response are not at the center of the squares), this is the same function you posted in your question, it works for me (the blue markers), I modified your click listener to open an infowindow (rather than do a redirect of the page):
function addMarkersAtRegionCenter(map, result) {
var length = result.regionList.length;
var regionUrl = "drilledDownToRegion.jsp?";
for (var i = 0; i < length; i++) {
var image = result.regionList[i].imageIcon;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(result.regionList[i].centerLatitude, result.regionList[i].centerLongitude),
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// window.location.href = marker.url;
infowindow.setContent("regionList:" + i + "<br>centLat=" + result.regionList[i].centerLatitude + "<br>centLng=" + result.regionList[i].centerLongitude + "<br>imageIcon=" + result.regionList[i].imageIcon + "<br>" + marker.getPosition().toUrlValue(6));
infowindow.open(map, marker);
}
})(marker, i));
}
}

How can i change the Marker color clicked previously to its original color

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>

Show all infowindows open

I'm trying to have custom infowindows float above markers, however I noticed that only one marker can be opened at any one time. Is there a workaround to this?
Here's the code I have produced at the moment:
downloadUrl("AllActivityxml.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("id");
var address = markers[i].getAttribute("id");
var type = markers[i].getAttribute("venue_type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng"))
);
var infowindow = new google.maps.InfoWindow();
var html = "<b>" + point + "</b>hello <br/>" + type;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map,marker);
});
}
});
And when you check this map, notice that I cannot open more than 2 infowindows at once. Why is that?
There is no limitation implicit to the Google Maps API v3 that makes only one InfowWindow available at a time. You need to write your code to do that. If you want an InfoWindow for each marker, make one.
Some thing like (not tested):
function createMarker(latlng, html) {
var contentString = html;
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}

Infowindow opens only for last JSON record

I am trying to display InfoWindow but the problem is that I'm only able to see the last record of JSON.
onmouseover shows the title of other 2 markers but their InfoWindows are not opening. Please suggest how to fix this code
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
Never mind, I was very dumb to not see it first. I was adding click event after the loop. All I needed to do was this.
var infoWindow = new google.maps.InfoWindow();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
i.e. closure had to be inside the loop