Draggable google map markers - javascript

I have been working with google maps and now have a requirement to make a draggable marker that I can place on the map.
Is this a big difference in complexity from just placing markers by geolocation coordinates? What is the best way of going about making draggable markers that users can set?
Thank you,
Alex

You dont mention which version of the API you are using, so i will asume v3... There is a draggable property that you can either set in the constructor using the options parameter 'draggable: true' or by invoking the setDraggable(true) function after it is created.
Check http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker for more info.
Edit: For version 2 there are enableDragging() and disableDragging() functions...
As for adding markers, perhaps subscribe to the mouse click event on the map, and then add a marker in there. The coordinates are passed into the event handling function as part of the event parameter.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(9.010951935679284, 38.760017580032354);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 15,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function () {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function () {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function () {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style type="text/css">
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<html>
<head>
<title></title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
</head>
<body>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>

Related

How to determine if map or marker is clicked

thanks again for the great here map API.
We are currently struggling how to determine if a marker or the map itself was clicked. We have added event listeners to both the map and the marker (added as group).
When we now click on the map, both eventlisteners are fired.
Do we miss something in the API docs? I think there should be a way to get correct information of what was clicked.
Map event listener
map.addEventListener('tap', (event) => {
action(event);
});
Marker event listener
marker.addEventListener('tap', (event) => {
action(event);
});
Thanks in advance.
Better stay with a single listener on the map object.
The key thing is to check the instance of the event.target :
map.addEventListener('tap', event => {
if (event.target instanceof H.map.Marker) {
// Some action. Typically, you want to use the data that you may have referenced
// in the marker creation code, or get the coordinates. Here we log the data
console.log( event.target.getData() );
}
}
Hey this small example works fine for me, I see in the docs there is not listener for tap, these are the supported listeners.
https://developers.google.com/maps/documentation/javascript/events
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Markers</title>
<style>
/* 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"></div>
<script>
var map, marker;
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
map.addListener('click', (event) => {
console.log(event, 'from map')
});
marker.addListener('click', (event) => {
console.log(event, 'from marker')
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
</body>
</html>

Google Maps Javascript - Resize event listener not being called

I've got a map in a hidden div that gets revealed by a button press. I was initially having issues but they were fixed by triggering a resize event. My issue now is that the map isn't centered on the position that I initialise the map with.
I want to add a map.setCenter(?) call in to the resize or bounds changed event listener but they never seem to be called. I've put alerts in each one to test but nothing happens.
EDIT: Example as requested...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#theButton {
position: absolute;
top: 0;
left: 400px;
padding: 10px;
background-color: orange;
z-index: 100;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="theButton" onclick="resizeMap();">Click Me</div>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Test Location!'
});
var getCen = map.getCenter();
var currentMapCenter = null;
google.maps.event.addListener(map, 'resize', function () {
currentMapCenter = map.getCenter();
alert("Resizing");
});
google.maps.event.addListener(map, 'bounds_changed', function () {
if (currentMapCenter) {
// react here
map.setCenter(currentMapCenter);
alert("Centering");
}
currentMapCenter = null;
});
}
function resizeMap() {
alert("Clicked");
google.maps.event.trigger(map, 'resize');
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
</body>
</html>
I have tested more deeply your code there is a problem with the scope of the var map
change declaration in this way (in window scope outside the function initMap local scope)
<script>
var map;
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
........
......
Otherwise map is not correctly referenced in ths other function eg:
function resizeMap() {
google.maps.event.trigger(map, 'resize');
In this function if you don't change the var declaration map is not referenced and the nothing can be triggered

what should i do to create custom menu appear when i click the marker instead of deleting it

here is my code i have done upto this point where when i add marker and hover it infowindow appears, but all of them has the same infowindow i need it to be change for each marker, second instead of clicking on the marker it gets deleted i want to creat a custom menu box on the top of marker where there should be options to add info and delete whe i click the marker.
<html>
<head>
<title>example</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<style type="text/css">
#map_canvas {
width: 100%;
height: 500px;
background-color: #CCC;}
#menu_bar{
width: 100%;
height: 150px;
position:absolute;
bottom:0px;
background-color:#008080;
border-top:1px solid red;}
body{
padding:0px;
margin:0px;}
</style>
<!-- google maps Scripting start -->
<script type="text/javascript">
var markers = [];
function initialize() {
var myLatlng = new google.maps.LatLng(44.5403, -78.5463);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// add marker to positon
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
// deleting
google.maps.event.addListener(marker, 'click', function(event) {
this.setMap(null);
});
// adding info window to gMaps
var infowindow = new google.maps.InfoWindow({
content: "holdings content area"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map, this);
});
// assuming you also want to hide the infowindow when user mouses-out
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<!-- google maps Scripting ends -->
</head>
<body>
<div id="map_canvas"></div>
<div id="menu_bar">
</div>
</body>
</html>
First create a menu or popup or whatever you want in a html copy this html into javascript variable, next create gMap infoWindow and set content to your custom design, in last step bind event to your marker and in that event open your infowindow.
var map = new google.maps.Map(document.getElementById('yourmap'), mapOptions);
var popup= '<div>Design your whatever styled popup you want</div>';
var infowindow = new google.maps.InfoWindow({
content: popup
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'ABC'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});

Displaying Latitude and Longitude on Marker click event

I want to alert latitude and longitude value based on marker position.
I am unable to do it.
I have recently started learning about google maps api. Please help me along.
In below code my marker is correctly moving between different location but not showing
their latitude and longitude values.
<html>
<head>
<base href="<%=basePath%>">
<style type="text/css">
#map_canvas {
height: 430px;
width: 980px;
position: static;
top: 100px;
left: 200px;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var marker;
function initialize() {
var latlng = new google.maps.LatLng(18.9647, 72.8258);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker == undefined){
marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP
});
}
else{
marker.setPosition(location);
}
map.setCenter(location);
google.maps.event.addListener(marker, "click", function (event) {
alert(this.position);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="1500px; 1000px"></div>
</body>
</html>
You don't want to create a separate event for displaying the event - make it part of the code that creates (or moves) the marker, as follows:
function placeMarker(location) {
if (marker == undefined){
marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP
});
}
else{
marker.setPosition(location);
}
map.setCenter(location);
alert(marker.position);
}
Rather than using an alert, you can get a much more beautiful effect by following the links given in this answer for a really cool tooltip effect. Definitely worth taking a look - the answer links both a tutorial and a demonstration.

Get User Location by Marking on Google Map

ALL
i wanna developing window contains map and allow user to mark his location and get longitude and latitude based on the marked location
any one has a suggestion ?
you can use google map v3 for this purpose..
Try this code, it creates a marker where the user clicks on the map
<!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>
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
you will be requried to use maps click event to get lat/lag.
check below code for same.
GEvent.addListener(map, "click", function(overlay, latLng)
{
// display the lat/lng in your form's lat/lng fields
document.getElementById("latFld").value = latLng.lat();
document.getElementById("lngFld").value = latLng.lng();
//code for adding marker
//post/ajax call to save location in Database
});

Categories