I’m developing a website that incorporates a Google map v3 and I would like to know how to programmatically close the infowindows that can be opened when the user clicks on the icons that are loaded with the map. I don’t mean the infowindows opened when the markers the site places on the map are clicked on.
Is this possible?
Thanks in advance
var marker = new google.maps.Marker({
map: $scope.map,
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: 'some text'
});
marker.addListener('mousedown', function() {
infowindow.open($scope.map, marker);
if (!marker.open) {
infowindow.open($scope.map, marker);
marker.open = true;
setTimeout(function() {
infowindow.close();
marker.open = false;
}, 2000);
} else {
infowindow.close();
marker.open = false;
}
});
In ur case u just have to replace marker with icon , icon or whatever must have a mousedown or click listener.
And marker.open & close is just a variable
Related
I've tried to load Google Maps with marker from server using Ajax and Api.
I've tried everything but I don't know where is problem.
Map is loaded but markers are not. I also enclose picture from Postman of my Api response.
PLEASE HELP ME. I will be so glad to you.
Here is the code:
$.ajax({
type: "GET",
url: 'http://localhost:8000/api/bicykel/',
dataType: "json",
success: function (data) {
$.each(data, function (marker, data) {
var latLng = new google.maps.LatLng(data.bicykels.lat, data.bicykels.lng);
bounds.extend(latLng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div class='pt-5 bg-dark p-4' style='width:300px';>"+"<h3>"+data.bicykels.name+"</h3>" + " " + data.bicykels.name+"</div>");
infoWindow.open(map, marker);
});
});
},
error: function (data) {
console.log('Please refresh the page and try again');
}
});
Here is the code of Api:
def customer_get_bicykel(request):
uzivatel = request.user.id
bicykels = BicykelSerializer(
Bicykel.objects.filter(),
many = True,
context = {"request": request}
).data
return JsonResponse({"bicykels": bicykels})
And also I enclose screen of api response:
Api Response
THANK YOU FOR EVRY HELP!
You're missing out to add the marker to the map. Quoting the google maps JS docs:
// To add the marker to the map, call setMap();
marker.setMap(map);
I am sure i have structured this wrong, but the event listener for "dragend" is not firing. When I change the event to bounds_changed or center_changed then it only fires on the initial page load. Is there anything that stands out as to why it is behaving like this?
I basically just want to call my searchStores() function everytime the map is repositioned so it becomes reactive to the user.
var map;
$(document).ready(function () {
var latlng = new google.maps.LatLng(36.2994410, -82.3409052);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// create the new map with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$("#btnSearch").click(function(){
//Convert Address Into LatLng and Retrieve Address Near by
convertAddressToLatLng($("#txtAddress").val());
});
//send user to print/save view on click
$("#saveAs").click(function() {
window.location.href = "https://54.90.210.118/test.html?address=" + $("#txtAddress").val() + '&radius=' + $("#radiusO").val();
});
//WHAT IS GOING ON WITH THIS GUY???
google.maps.event.addListener(map, "dragend", function() {
alert('map dragged');
});
});
$(document).one('ready', function(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
latlngloc = new google.maps.LatLng(pos.lat, pos.lng);
map.setCenter(pos);
$("#divStores").html('');
searchStores(latlngloc);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
});
Thanks for the help! I found the issue was on another function that ended up clearing the map object and then recreating it. Therefore removing the listener.
Sorry for the confusion, and thanks for pointing out that it worked on Jfiddle. I thought it was something to do with how I was calling it.
I am really new to Javascript and having to teach myself bit by bit. Thanks for all the help! =)
I'm trying to build a tracker that only requires a browser window be open, on mobile devices. All of the code seems to work, other than navigator.gelocation.getCurrentPosition. As you can see, I'm using a timer to cycle my code every few seconds. I was expecting the code within the time to output real-time location information, but instead, it seems to resort to using the last known location - or if there isn't one, it will find the location and then keep using the same one.
I'm not sure if this is an issue with Android or my code, but it seemed to work well on an iPhone - but it wasn't me who tested it, so I can't really be sure.
Thanks in advance!
var lati = " ";
var longi = " ";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 15
});
var timerID = setInterval(function() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
var infoWindow = new google.maps.InfoWindow({map: map});
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
lati = (position.coords.latitude);
longi = (position.coords.longitude);
console.log(lati, "Lol");
infoWindow.setPosition(pos);
infoWindow.setContent('lati');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
//in a loop (setInterval) get coords and apply them to database
{
$.ajax({ url: 'php_test.php',
data: {'Lati': lati, 'Longi': longi},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
}
});
}
}, 2 * 1000);
}
I'm facing the same issue but I realize debugging that getCurrentPosition is deprecated on insecure origins.
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
Maybe you can achieve something like How do I get the current GPS location programmatically in Android?
Is there any event to check if user end zoomed in a map or end zoomed out the map
What we do is.. we want to send the latitude or longtitude to server when they making change to the map. for example when they end dragging we will send the latitude and longtitude to server to load some shop location that are within boundary of that latitude and longtitude and we will put the pins on it. so all the possible event are user dragging map, zoom in, zoom out and scrolling. we will not use bounds_changed event because it will send data to the server all the time.
//Get bound of the map when a user dragged the map.
google.maps.event.addListener(map, 'dragend', function () {
bound = map.getBounds();
var latlng_NE = bound.getNorthEast();
var latlng_SW = bound.getSouthWest();
// Some code to send latitude or longtitude to server here
throw new Error(latlng_NE, latlng_SW);
});
From the Google Maps API doc
google.maps.event.addListener(map, 'zoom_changed', function() {
setTimeout(moveToDarwin, 3000);
});
https://developers.google.com/maps/documentation/javascript/events;
edit
// closure
(function() {
var timeout = null;
var delay = 500;
function react() {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(react, delay)
}
function sendBoundsToServer() {
bound = map.getBounds();
var latlng_NE = bound.getNorthEast();
var latlng_SW = bound.getSouthWest();
// some AJAX action to send bound to server
// ...
}
//Action after a user dragged the map.
google.maps.event.addListener(map, 'zoom_changed', function () {
// Some code to send latitude or longtitude to server here
setTimeout(sendMessageToServer, 1000)
});
google.maps.event.addListener(map, 'dragend', function () {
// Some code to send latitude or longtitude to server here
setTimeout(react, 1000)
});
// Add more events here like the two above
}())
With the Google Maps JS API v3, I want to drop a marker where the user clicks on the map, while keeping the default behavior when the user double clicks (and not adding any marker on the map).
I thought about defining a timeout on click event. If a double click event is triggered within the next few milliseconds, the timeout is cancelled. If not, the marker is placed on the map when the timeout expires.
But it doesn't really look like the best solution ever.
Is there a more elegant way to handle this?
Thanks.
I just found an hackish solution which works but introduce a small waiting time (200ms, this is the minimum to make it work, but I don't know if it is client dependent)
var update_timeout = null;
google.maps.event.addListener(map, 'click', function(event){
update_timeout = setTimeout(function(){
do_something_here();
}, 200);
});
google.maps.event.addListener(map, 'dblclick', function(event) {
clearTimeout(update_timeout);
});
Hope this helps!
The easiest way to solve it.
var location;
var map = ...
google.maps.event.addListener(map, 'click', function(event) {
mapZoom = map.getZoom();
startLocation = event.latLng;
setTimeout(placeMarker, 600);
});
function placeMarker() {
if(mapZoom == map.getZoom()){
new google.maps.Marker({position: location, map: map});
}
}
shogunpanda's solution is better (see below)
You can take advantage of, dblclick fires if it is a double click, and single click fires in such occations only once.
runIfNotDblClick = function(fun){
if(singleClick){
whateverurfunctionis();
}
};
clearSingleClick = function(fun){
singleClick = false;
};
singleClick = false;
google.maps.event.addListener(map, 'click', function(event) {// duh! :-( google map zoom on double click!
singleClick = true;
setTimeout("runIfNotDblClick()", 500);
});
google.maps.event.addListener(map, 'dblclick', function(event) {// duh! :-( google map zoom on double click!
clearSingleClick();
});
See http://www.ilikeplaces.com
If you're using underscore.js or* lodash here's a quick and elegant way to solve this problem
// callback is wrapped into a debounce function that is called after
// 400 ms are passed, it provides a cancel function that can be used
// to stop it before it's actually executed
var clickHandler = _.debounce(function(evt) {
// code called on single click only, delayed by 400ms
// adjust delay as needed.
console.debug('Map clicked with', evt);
}, 400);
// configure event listeners for map
google.maps.event.addListener(map, 'click', clickHandler);
google.maps.event.addListener(map, 'dblclick', clickHandler.cancel);
* Debounce.cancel is implemented only in lodash (with this commit), underscore.js does not implement it
A cleaner way to implement the setTimeout() approach is to trigger custom events for single clicks.
The following function takes any Google Maps interface object (e.g. map, marker, polygon etc.) and sets up two custom events:
singleclick: called 400ms after a click if no other clicks have occured
firstclick: called whenever a click event occurs, unless a click has already occured in the last 400ms (this is handy for showing some kind of immediate click feedback to the user)
function addSingleClickEvents(target) {
var delay = 400;
var clickTimer;
var lastClickTime = 0;
google.maps.event.addListener(target, 'click', handleClick);
google.maps.event.addListener(target, 'dblclick', handleDoubleClick);
function handleClick(e) {
var clickTime = +new Date();
var timeSinceLastClick = clickTime - lastClickTime;
if(timeSinceLastClick > delay) {
google.maps.event.trigger(target, 'firstclick', e);
clickTimer = setTimeout(function() {
google.maps.event.trigger(target, 'singleclick', e);
}, delay);
} else {
clearTimeout(clickTimer);
}
lastClickTime = clickTime;
}
function handleDoubleClick(e) {
clearTimeout(clickTimer);
lastClickTime = +new Date();
}
}
You can use it like so:
var map = ....
addSingleClickEvents(map);
google.maps.event.addListener(map, 'singleclick', function(event) {
console.log("Single click detected at: " + event.latLng);
}
I'm not sure, but if you add event handlers to both 'click' & 'dblclick' events, where you say to put marker on a click, and don't take any action on double click, then you can skip the adding of timeouts (the maps API can differ what is click and what is double click)
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map, 'dblclick', function(event) {
//DO NOTHING, BECAUSE IT IS DOUBLE CLICK
});
The placeMarker(latLng) is custom added function which adds marker on the given location:
var marker = new google.maps.Marker({
position: location,
draggable: true,
map: map
});
map.setCenter(location);