Adding pin to location clicked - javascript

I've got the following Google map on my website..
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(53.347247,-6.259031), 13);
map.setUIToDefault();
GEvent.addListener(map, "click", function(overlay, latLng)
{
// display the lat/lng in your form's lat/lng fields
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
});
}
}
What would I need to add / edit so that whenever a user clicked a location on the map a pin / balloon / any kind of indicator would be dropped at the location they clicked?
Thanks.

All you have to do is add this to your existing addListener call:
if (latLng) {
marker = new GMarker(latLng, {draggable:true});
map.addOverlay(marker);
}
See this article linked by Google in their API information for an even more advanced example that lets your users edit the map data.
Update: Changed case of 'l' to 'L' in latLng.

Related

Leaflet Update Single Marker

I have a Leaflet OpenStreetMap map where I set a new marker. I want the marker to move, which would mean clearing all previous markers, and adding a new one. Currently new clicks just result in new markers, with more than one staying on the map.
How can I clear all markers upon clicking again?
initmap();
var home = new L.LayerGroup();
map.on('click', function(e) {
// clear all markers here somehow
document.getElementById("latFld").value = e.latlng.lat;
document.getElementById("lngFld").value = e.latlng.lng;
L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);
});
Edit:
My original markers did not belong to a group.
L.marker([43.653409, -79.384112]).bindPopup('Original Home').addTo(map);
Regardless of the LayerGroup into a variable, I was asking if there was a way to clear all markers regardless. It is not a duplicate.
Shoved my markers into a layerGroup so I can use that for clearing:
var mymarkers = L.layerGroup([
L.marker([43.677681,-79.389943]).bindPopup('Some place'),
L.marker([<%= #mylat %>,<%= #mylon %>]).bindPopup('Original Home')
]);
L.control.layers(mymarkers).addTo(mymap);
mymap.on('click', function(e) {
mymarkers.clearLayers();
document.getElementById("latFld").value = e.latlng.lat;
document.getElementById("lngFld").value = e.latlng.lng;
L.marker([e.latlng.lat,e.latlng.lng]).bindPopup('New ome').addTo(mymarkers);
$('#update').html("Values updated");
});
I was expecting an object that automatically held all markers, but it wasn't there. So I had to assign then to one.

Hide markers from google maps when click an external link and only show its corresponding marker

How do i change my center for google maps with a link and remove other markers? i have this code
https://jsfiddle.net/m9ugbc7h/
So, i need to create a link for example
Ventura
In this case the function must change google maps center to focus the "ventura" marker and hide the other markes and when the user clicks on
Dolphinaris
the zoom will change and will hide every other marker and show only the ones of Dolphinaris
Thanks in advance
Make map visible outside of jQuery(document).ready.
Create var markers = []; array.
When crating markers, add custom property name to it, and push marker into markers array:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(21.0241839, -86.8148164),
map: map,
visible: true,
icon: ventura,
name: 'ventura',
});
markers.push(marker);
On click, invoke resetMap() function:
Ventura
Inside resetMap function, set center and zoom to map, iterate markers, matching them by custom property name - matched one set visible, others set to invisible.
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
map.setCenter(newPos);
map.setZoom(zoom);
markers.forEach(function(marker) {
if(marker.get('name') == name)
{
console.log('match');
marker.setVisible(true);
}
else
{
marker.setVisible(false);
}
});
Working fiddle: https://jsfiddle.net/m9ugbc7h/1/
EDIT:
Question: "is there any way to change smoothly the zoom and coordinates?"
Yes, use method:
panTo(latLng:LatLng|LatLngLiteral)
Changes the center of the map to the given LatLng. If the change is
less than both the width and height of the map, the transition will be
smoothly animated.
https://developers.google.com/maps/documentation/javascript/reference?csw=1
EDIT 2:
Implementing panTo is easy:
map.panTo(newPos);
instead of:
map.centerTo(newPos);
but as I have faced a bit 'flickering' effect due to hide/show markers that are close on the map, I have added some delay in functions invocation + markers show/hide:
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
$.when( map.setZoom(zoom) ).done(function(){
$.when( map.panTo(newPos)).done(function(){
setMarkerVisibility(name);
});
});
}
And showing matched marker is now executed with 300 ms delay:
function setMarkerVisibility(name){
markers.forEach(function(marker) {
console.log(marker.get('name'));
if(marker.get('name') == name)
{
setTimeout(function(){ marker.setVisible(true); }, 300);
}
else
{
marker.setVisible(false);
}
});
}
It looks a bit smoother like this.
Working fiddle: https://jsfiddle.net/m9ugbc7h/3/

How to keep info-window of particular marker displayed on cluster?

I'm using Google Maps Javascript v3 API and MarkerClusterer JS in my Ruby on Rails application.
I want following functionality in my map. I've some markers on my map, in that map markers forms a cluster when I zoom out the map, and again gets separated when I zoom in. When I click on the particular marker it displays the info-window of that marker, and when I click on the cluster it displays the info-window related to that cluster. this is the current behavior of my map.
Now when I click on the particular marker on the map, it displays the info-window of that marker, now I zoom out that and when the marker becomes the part of cluster then the info-window of that marker is hidden, I want that info-window to remain displayed on cluster also.
I'm using global info-window for markers and clusters.
here is the some code that handles map in my application.
function createMarker(latlng, name, html) {
// create new google marker using the latitude and longitude that is passed into this function as "latlng"
var marker = new google.maps.Marker({
position: latlng,
draggable: true ,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5,
icon: '/assets/pin.png',
});
// add click event listner to the created marker
google.maps.event.addListener(marker, 'click', function() {
// clear the previous content of infowindow
infowindow.setContent('');;
// close the infowindow
infowindow.close();
// set the content of infowindow that is passed into this function as "html"
infowindow.setContent(html);
// open the new infowindow with the created marker
infowindow.open(map,marker);
clearUpMenus();
});
// add closeclick event listner when user clicks on the close button on the infowindow
google.maps.event.addListener(infowindow,'closeclick',function(){
// set the map of the marker to null
marker.setMap(null);
check = null;
});
// add drag event listner when user drags the created marker
google.maps.event.addListener(marker,'dragend',function(event) {
// update latitude and longitude of the marker with the dragged ones.
var lat = event.latLng.lat();
var lng = event.latLng.lng();
// set latitude and longitude to the input fields for further uses.
form_latitude = lat;
form_longitude = lng;
$("input[id=location_latitude]").val(lat);
$("input[id=location_longitude]").val(lng);
});
// trigger the click event manually
google.maps.event.trigger(marker, 'click');
// return the created marker
return marker;
}
Above is the code to create the new marker on my map.
var markerCluster = new MarkerClusterer(map,markersArray, clusterOptions);
google.maps.event.addListener(markerCluster, 'click', function(cluster) {
// this function displays the info-window on cluster
displayClusterInfo(cluster);
});
function displayClusterInfo(cluster) {
var markers = cluster.getMarkers();
$('.map-title').css('z-index',-1);
map.setOptions({zoomControl:false, streetViewControl:false});
var info = new google.maps.MVCObject;
info.set('position', cluster.getCenter());
//getTopThreeMarkers() - It makes the ajax call to get top markers based on some criteria
getTopThreeMarkers(info,markers);
}
Any help would be appreciated.
Thanks.

How to find accurate LatLng values of google map

In my App,user can find place Name using click event,after getting place Name,I am showing the place name to user with inputFieldFor this I written the following code.
//helper function
function makingGeocodeRequest(obj,callback){
var geocodeInstance=new google.maps.Geocoder();
geocodeInstance.geocode(obj,callback);
}
google.maps.event.addListener(mapInstane,"click",function(event){
makingGeocodeRequest(_.object(["location"],[event.latLng]),
function(res,status){
document.getElementById("field").value=res[0]["formatted_address"];
}
)
})
Once user click on Save button.I am finding latlng value based on place Name.using the following code
makingGeocodeRequest(
_.object(["address"],[document.getElementById("field").value]),
function(res,status){
if (status===google.maps.GeocoderStatus.OK) {
var latLngObj=res[0]["geometry"]["location"];
console.log(latLngObj;
}
}
)
The problem here,both latlng values are different(click event time latlng value and save button action latlng value).
Actually both are finding from Google,but it's returning different latlng values.
While click event event,I am changing cursor style with this Icon.After click on Save button reverting default cursor.
How can I fix this.Can anyone help me.
Thanks.
To solve your problem you can create and array of points, add marker to this array and render results of the array on the map.
Here is how you can do this :
With Javascript,
<script type="text/javascript">
var map;
var markersList= [];
function initGMap()
{
var latlng = new google.maps.LatLng(39, 20);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// add a click event handler to the map object and get the lat Lng and then place it on the map
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latVal").value = event.latLng.lat();
document.getElementById("lngVal").value = event.latLng.lng();
});
}
// here is the function to place Marker on the map
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersList.push(marker);
//map.setCenter(location);
}
// Here you can use this function to delete all markers in the array
function deleteOverlays() {
if (markersList) {
for (i in markersList) {
markersList[i].setMap(null);
}
markersList.length = 0;
}
}
</script>
With Html code,
<body onload="initGMap()">
<div id="map"></div>
<input type="text" id="latVal">
<input type="text" id="lngVal">
</body>

Google Maps with cluster of markers and their info window

I have a cluster of Google map marker’s. I am showing Google maps in a ModalPopupExtender on a button click. After map is loaded with marker’s I want to pop up info window on mouse over of marker’s. how can I keep the details of info window of each marker when map is loading with marker’s?.
$('#map-canvas').fadeIn('slow', function() {
google.maps.event.trigger(map, 'resize');
for (var i = 0; i < asGridselectedRows.length; i++) {
var row = asGridselectedRows[i];
var Latitude = asGridMasterTable.getCellByColumnUniqueName(row, "Latitude");
var Longitude = asGridMasterTable.getCellByColumnUniqueName(row, "Longitude");
var messno = asGridMasterTable.getCellByColumnUniqueName(row, "MessNo");
var messnumber = messno.innerHTML.substring(6, messno.innerHTML.length - 7);
var Lat = Latitude.innerHTML.substring(6, Latitude.innerHTML.length - 7);
var Long = Longitude.innerHTML.substring(6, Longitude.innerHTML.length - 7);
var myLatLng = new google.maps.LatLng(Lat, Long);
map.setCenter(myLatLng);
map.setZoom(13);
marker = new google.maps.Marker({
map: map
});
if (messnumber == '00')
{
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
}
else
{
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png');
}
marker.setPosition(myLatLng);
marker.setVisible(true);
}
});
You need to build the info window as part of the event listener. See the example given in the answer here: Changing data in the info window with Google Map markers
You can add attributes to each marker so that these can be referenced in the hover event. In your case it looks like you could simply use the messno as an attribute and then reference your data table with the marker info in

Categories

Resources