How to get position of cursor when dragging? - javascript

I am working with Google map v3.
And i am newbie with java script.
have anyone know how to get position of cursor on web browser when dragging( before and after dragging)?
Please teach me.

The best alternative I have is tracking the movement of the map's center point (latitude, longitude). Drag events don't seem to provide the mouse location on the map.
View here: http://jsfiddle.net/Hfu8D/
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body, #map_canvas { margin: 0; padding: 0; height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'dragstart', function(event) {
document.getElementById("start").value = map.getCenter();
});
google.maps.event.addListener(map, 'dragend', function(event) {
document.getElementById("end").value = map.getCenter();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
start: <input id="start" size="30"><br>
end: <input id="end" size="30">
<div id="map_canvas"></div>
</body>
</html>

You can use the mousemove event for the map and add an event listener that updates a text box (or any other element) in real-time as the cursor moves.
Here's an example (forked from Mia's JS Fiddle):
http://jsfiddle.net/76VLh/3/

Related

How to get LAT and LNG from google map javascript to html input and add marker

I have a google map location picker that works fine and returns LAT and LNG but I will like to add the LAT and LNG into the HTML input field when the location is picked. Below is what my code looks like:
<!DOCTYPE html>
<html>
<head>
<title>Event Click LatLng</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
<script type="text/javascript">
function initMap() {
const myLatlng = { lat: 24.466667, lng: 54.366669 };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: myLatlng,
});
// Create the initial InfoWindow.
let infoWindow = new google.maps.InfoWindow({
content: "Click the map to get Lat/Lng!",
position: myLatlng,
});
infoWindow.open(map);
// Configure the click listener.
map.addListener("click", (mapsMouseEvent) => {
// Close the current InfoWindow.
infoWindow.close();
// Create a new InfoWindow.
infoWindow = new google.maps.InfoWindow({
position: mapsMouseEvent.latLng,
});
infoWindow.setContent(
JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
);
infoWindow.open(map);
});
}
</script>
<style type="text/css">
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map" style="height: 500px;"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly&channel=2"
async
></script>
<input type="text" name="lat" id="lat">
<input type="text" name="lng" id="lng">
</body>
</html>
As you can see from above, there is an infoWindow that gets the LNG and LAT when a location is clicked on the map but now I want where a location is click it get the LNG to the input field<input type="text" name="lng" id="lng"> and LAT to <input type="text" name="lat" id="lat">
Add the following to your click listener:
document.getElementById('lat').value = mapsMouseEvent.latLng.lat();
document.getElementById('lng').value = mapsMouseEvent.latLng.lng();
code snippet:
function initMap() {
const myLatlng = {
lat: 24.466667,
lng: 54.366669
};
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: myLatlng,
});
// Create the initial InfoWindow.
let infoWindow = new google.maps.InfoWindow({
content: "Click the map to get Lat/Lng!",
position: myLatlng,
});
infoWindow.open(map);
// Configure the click listener.
map.addListener("click", (mapsMouseEvent) => {
// Close the current InfoWindow.
infoWindow.close();
// Create a new InfoWindow.
infoWindow = new google.maps.InfoWindow({
position: mapsMouseEvent.latLng,
});
document.getElementById('lat').value = mapsMouseEvent.latLng.lat();
document.getElementById('lng').value = mapsMouseEvent.latLng.lng();
infoWindow.setContent(
JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
);
infoWindow.open(map);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Event Click LatLng</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
<input type="text" name="lat" id="lat">
<input type="text" name="lng" id="lng">
</body>
</html>
Right now you have
infoWindow.setContent(
JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
);
Which as you said puts the latlng info into the infoWindow. It sounds like that works correctly. So it should just be a matter of adding
document.querySelector("#lat").value = mapsMouseEvent.latLng.lat;
document.querySelector("#lng").value = mapsMouseEvent.latLng.lng;
You can put that within the map.click handler, right after infoWindow.setContent, or in place of it.

Google Maps API v3 Custom Button moving around

JSFiddle reproducing the issue.
I am adding a custom button to the top center of the map. I have a click event attached to the map that will fadeIn the button. A rightclick event on the map that will fadeOut the button.
To reproduce the issue:
Right click on the map to fadeOut the button.
Increase/decrease zoom level by at least one level.
Left click to fadeIn the button.
At this point the button will fade back in at a location different
than its original location.
Increase/decrease zoom level by at least one level.
You will then see the button snap back to its original location.
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(41.508742, -0.120850),
zoom: 7,
disableDefaultUI: true
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var btn = document.getElementById('myButton');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(btn);
map.addListener('click', function() {
jQuery('#myButton').fadeIn();
});
map.addListener('rightclick', function() {
jQuery('#myButton').fadeOut();
});
.button {
display: block;
}
#map {
width: 300px;
height: 300px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div id="map"></div>
<button class="button" id="myButton">asdf</button>
<script src="https://maps.googleapis.com/maps/api/js?callback=myMap"></script>
</body>
</html>
That looks like a potential bug with the control positions on the Map object. You may want to file a bug on Google's Public Issue Tracker.
As a workaround, you could try removing the button on the rightclick from the Map controls (with a slight timeout to let the fadeout effect complete), then readding it back to the map on the left click.
Simple sample JSBin
<!DOCTYPE html>
<html>
<head>
<title>Google Maps Custom Controls</title>
<style>
.button {
display: block;
width: 70px;
}
#map {
width: 300px;
height: 300px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_KEY" async defer></script>
<script>
function initMap() {
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(41.508742, -0.120850),
gestureHandling: 'greedy',
zoom: 7,
disableDefaultUI: true
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var btn = document.getElementById('myButton');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(btn);
map.addListener('click', function() {
if (!jQuery('#myButton').is(":visible")) {
map.controls[google.maps.ControlPosition.TOP_CENTER].push(btn);
jQuery('#myButton').fadeIn();
}
});
map.addListener('rightclick', function() {
if (jQuery('#myButton').is(":visible")) {
jQuery('#myButton').fadeOut();
setTimeout(function(){ map.controls[google.maps.ControlPosition.TOP_CENTER].pop(btn); }, 500)
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<button class="button" id="myButton">asdf</button>
</body>
</html>

zoom_changed listener doesn't work for me

I'm trying to use a zoom listener event in a google maps so that I can resize some axis I have in it. As a beginning, I'm trying to use an alert so that I can see whether if the listener detects a change in the zoom level or not, but I'm not able to get any alert at all. My code is the following:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - pygmaps </title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>
<script type="text/javascript">
var map;
function initialize() {
var centerlatlng = new google.maps.LatLng(49.801674, 11.188139);
var myOptions = {
zoom: 18,
center: centerlatlng,
scaleControl:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
* plotting stuff *
google.maps.event.addDomListener(window, 'load',initialize);
google.maps.event.addDomListener(maps,'zoom_changed', function()
{
alert("changed");
});
</script>
</head>
<body>
<div style="text-align:center;">
<button onclick="draw_axis()">Enable/Disable Axis</button> <br><br> <div id="log"></div>
</div>
<div id="map_canvas" style="width: 100%; height: 90%;"></div>
</body>
</html>
Does anyone see the problem?
The map variable isn't defined when you create the zoom_changed listener, it is created later, when the initialize function runs (also the variable is map, not maps).
code snippet:
var map;
function initialize() {
var centerlatlng = new google.maps.LatLng(49.801674, 11.188139);
var myOptions = {
zoom: 18,
center: centerlatlng,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addDomListener(map, 'zoom_changed', function() {
alert("changed");
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div style="text-align:center;">
<div id="log"></div>
</div>
<div id="map_canvas" style="width: 100%; height: 90%;"></div>
You need to set zoom_changed event on the instance of google.maps.Map inside your initialize() function.
map.addListener('zoom_changed', function() {
alert("changed");
});

Google Maps assign a php pop-up window on clicking a marker

Assume I have put a marker at a specific location on the Map.
I want the program to open a pop-up window called bla.php when the user click on this marker.
This is what I already done to put the marker:
<!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="https://maps.googleapis.com/maps/api/js?key=AIzaSyDxVucBtLP4XefoM4syoigBgXntwkVGxv8&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(48, 2),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var position = new google.maps.LatLng(48,2);
var marker = new google.maps.Marker({
position: position,
map: map
});
marker.setTitle("pv-unit");
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
I tried it, the whole map is not loading
First you need an event listener for your marker. Then within that, whatever code you want for opening a popup, e.g.
google.maps.event.addListener(marker, 'click', function() {
window.open('blah.php','name','height=200,width=150');
});

Placing a marker in Google maps

So I am preparing a page which has a Google Map and there are two forms namely latitude and longitude , and a submit button.
On entering the longitude and latitude the map is centered to the desired location and puts a marker there.
The problem I am facing is that whenever I put a new lat/long , the old marker won't go.
So basically if entered first lat/long : 10/12 , it would center to that and place a marker there, but when i enter the second lat/long (say) : 11/12 , it would center to that too and place a marker there also while the first one is not removed.
I want the page to be whenever the a new entered in the form only that one reflects in the form no old markers.
Here's my CODE :
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<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 initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
Some help would be useful
You need to clear markers each time in order to do that.
To clean marker keep marker as global variable, eg.
function pan() {
try{
marker.setMap(null);//clear marker
}
catch(err){
}
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
//declare marker as global variable
marker = new google.maps.Marker({
map: map,
position: panPoint,
});
}
That should do the trick.
use this code
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<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;
var markersArray=[];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(11.6667,76.2667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
function pan() {
deleteOverlays();
var panPoint = new google.maps.LatLng(document.getElementById("lat").value, document.getElementById("lng").value);
map.setCenter(panPoint)
var marker = new google.maps.Marker({
map: map,
position: panPoint,
});
markersArray.push(marker);
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
</head>
<body>
Latitude:<input type="text" id="lat" >
Longitude:<input type="text" id="lng">
<input type="button" value="updateCenter" onclick="pan()" />
<div id="map-canvas"></div>
</body>
</html>
In the pan function before adding the new marker, try to remove all the present markers Google Maps API v3: How to remove all markers?

Categories