I want to enable drawing on Google Maps like (see this example)
When user finish with drawings he will click on save button to save his drawings in Database or KML file, anything :) .. I do not know how to the save part? Could anyone help me
Here, http://jsfiddle.net/X66L4/1/ try drawing some circles, click on SAVE, then edit the circles by switching to the hand cursor and SAVE again to see the changes.
I show an example to save circles' data, the main idea is to keep a global array for each drawing type (line, polygon, marker, circle), and use a listener on the drawing manager to detect each type being drawn (complete).
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete',
function(circle) {
circles.push(circle);
});
The reason to save the entire reference to the drawn object is to continue tracking changes. So you will need an array and listener for each type of drawing.
Then, when you want to save the data (you may wish to do so at every edit), iterate through the arrays and extract the minimum information to rebuild it (center, radius, path, latLng, and so on.)
<!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&libraries=drawing"></script>
<script type="text/javascript">
var myOptions = {
center: new google.maps.LatLng(-25,177.5),
zoom: 3,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map;
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.CIRCLE,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [google.maps.drawing.OverlayType.CIRCLE]
},
circleOptions: {
editable: true
}
});
drawingManager.setMap(map);
var circles = [];
google.maps.event.addDomListener(drawingManager, 'circlecomplete', function(circle) {
circles.push(circle);
});
google.maps.event.addDomListener(savebutton, 'click', function() {
document.getElementById("savedata").value = "";
for (var i = 0; i < circles.length; i++) {
var circleCenter = circles[i].getCenter();
var circleRadius = circles[i].getRadius();
document.getElementById("savedata").value += "circle((";
document.getElementById("savedata").value +=
circleCenter.lat().toFixed(3) + "," + circleCenter.lng().toFixed(3);
document.getElementById("savedata").value += "), ";
document.getElementById("savedata").value += circleRadius.toFixed(3) + ")\n";
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<button id="savebutton">SAVE</button>
<textarea id="savedata" rows="8" cols="40"></textarea>
<div id="map_canvas"></div>
</body>
</html>
In my experience, it's easier to use map's dataLayer then the drawing manager.
Try out this fiddle.
FiddleLink
Showing the controls:
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
in this function you can see the Create, Read (localStorage) and Remove (not in that order):
function loadPolygons(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.forEach(function (f) {
map.data.remove(f);
});
console.log(data);
map.data.addGeoJson(data)
}
Related
I'm using this code to capture the co-ordinates when user clicks on the map by using below event listener:
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
However this function doesn't get called when user click on already marked location in Map.
Meaning this function is not called for points where mouse pointer changes to hand icon on Google Map.
Need help on capturing these kind of locations.
You should add the click listener on marker will give you the position of marker.
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
}); //end addListener
Edit:
You need something like this
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
radius = new google.maps.Circle({map: map,
radius: 100,
center: event.latLng,
fillColor: '#777',
fillOpacity: 0.1,
strokeColor: '#AA0000',
strokeOpacity: 0.8,
strokeWeight: 2,
draggable: true, // Dragable
editable: true // Resizable
});
// Center of map
map.panTo(new google.maps.LatLng(latitude,longitude));
}); //end addListener
Another solution is to place a polygon over the map, same size as the map rectangle, and collect this rectangles clicks.
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var lat1 = 37.41463623043073;
var lat2 = 37.46915383933881;
var lng1 = -122.1848153442383;
var lng2 = -122.09898465576174;
var rectangle = new google.maps.Polygon({
paths : [
new google.maps.LatLng(lat1, lng1),
new google.maps.LatLng(lat2, lng1),
new google.maps.LatLng(lat2, lng2),
new google.maps.LatLng(lat1, lng2)
],
strokeOpacity: 0,
fillOpacity : 0,
map : map
});
google.maps.event.addListener(rectangle, 'click', function(args) {
console.log('latlng', args.latLng);
});
});
}
Now you get LatLng's for places of interest (and their likes) also.
demo -> http://jsfiddle.net/qmhku4dh/
You're talking about the Point of Interest icons that Google puts on the map.
Would it work for you to remove these icons entirely? You can do that with a Styled Map. To see what this would look like, open the Styled Map Wizard and navigate the map to the area you're interested in.
Click Point of interest under Feature type, and then click Labels under Element type. Finally, click Visibility under Stylers and click the Off radio button under that.
This should remove all of the point of interest icons without affecting the rest of the map styling. With those gone, clicks there will respond to your normal map click event listener.
The Map Style box on the right should show:
Feature type: poi
Element type: labels
Visibility: off
If the result looks like what you want, then click Show JSON at the bottom of the Map Style box. The resulting JSON should like this this:
[
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
You can use that JSON (really a JavaScript object literal) using code similar to the examples in the Styled Maps developer's guide. Also see the MapTypeStyle reference for a complete list of map styles.
This example demonstrates the use of click event listeners on POIs (points of interest). It listens for the click event on a POI icon and then uses the placeId from the event data with a directionsService.route request to calculate and display a route to the clicked place. It also uses the placeId to get more details of the place.
Read the google documentation.
<!DOCTYPE html>
<html>
<head>
<title>POI Click Events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<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;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="infowindow-content">
<img id="place-icon" src="" height="16" width="16">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script>
function initMap() {
var origin = {lat: -33.871, lng: 151.197};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: origin
});
var clickHandler = new ClickEventHandler(map, origin);
}
/**
* #constructor
*/
var ClickEventHandler = function(map, origin) {
this.origin = origin;
this.map = map;
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
this.placesService = new google.maps.places.PlacesService(map);
this.infowindow = new google.maps.InfoWindow;
this.infowindowContent = document.getElementById('infowindow-content');
this.infowindow.setContent(this.infowindowContent);
// Listen for clicks on the map.
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function(event) {
console.log('You clicked on: ' + event.latLng);
// If the event has a placeId, use it.
if (event.placeId) {
console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
this.calculateAndDisplayRoute(event.placeId);
this.getPlaceInformation(event.placeId);
}
};
ClickEventHandler.prototype.calculateAndDisplayRoute = function(placeId) {
var me = this;
this.directionsService.route({
origin: this.origin,
destination: {placeId: placeId},
travelMode: 'WALKING'
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
ClickEventHandler.prototype.getPlaceInformation = function(placeId) {
var me = this;
this.placesService.getDetails({placeId: placeId}, function(place, status) {
if (status === 'OK') {
me.infowindow.close();
me.infowindow.setPosition(place.geometry.location);
me.infowindowContent.children['place-icon'].src = place.icon;
me.infowindowContent.children['place-name'].textContent = place.name;
me.infowindowContent.children['place-id'].textContent = place.place_id;
me.infowindowContent.children['place-address'].textContent =
place.formatted_address;
me.infowindow.open(me.map);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
If you are using npm load-google-maps-api with webpack this worked for me:
const loadGoogleMapApi = require("load-google-maps-api");
loadGoogleMapApi({ key: process.env.GOOGLE_MAP_API_KEY }).then(map => {
let mapCreated = new map.Map(mapElem, {
center: { lat: lat, lng: long },
zoom: 7
});
mapCreated.addListener('click', function(e) {
console.log(e.latLng.lat()); // this gives you access to the latitude value of the click
console.log(e.latLng.lng()); // gives you access to the latitude value of the click
var marker = new map.Marker({
position: e.latLng,
map: mapCreated
});
mapCreated.panTo(e.latLng); // finally this adds red marker to the map on click.
});
});
Next if you are integrating openweatherMap in your app you can use the value of e.latLng.lat() and e.latLng.lng() which I console logged above in your api request. This way:
http://api.openweathermap.org/data/2.5/weather?lat=${e.latLng.lat()}&lon=${e.latLng.lng()}&APPID=${YOUR_API_KEY}
I hope this helps someone as it helped me.
Cheers!
Hello and thanks in advance for your help!
The following test code:
1) Uses PHP to get lat/lng data from a mySQL database, and then uses that data to form a JavaScript array with initialization data. WORKS FINE.
2) Uses the initialized JavaScript array to create markers. WORKS FINE.
3) Allows (left) clicks to create new markers (more code will be added later to add those new marker locations back into the database). WORKS FINE.
4) Allows RIGHT-clicks to delete a marker using marker.setMap(null) - either the preloaded markers from the database, or newly created user markers. USER MARKERS DELETE PROPERLY, PRE-LOADED MARKERS DO NOT DELETE PROPERLY, AS DESCRIBED BELOW.
5) Both the preloaded markers, and the newly created ones are stored in the array "markers" using the statement markers.push(marker). SEEMS TO BE OK.
Everything works, except the right-click deletion of the PRELOADED markers. (The right-click deletion of user created markers works fine.) Any right-click on any preloaded marker, only deletes the LAST preloaded marker. It's as if the delete event listener were outside and after the loop that sets the preloaded markers, but it is inside that loop.
I think the faulty section is the one with the leading comment "show prev clicks in database". Any ideas would be greatly appreciated! I'm very new at Google Maps API v3, so it's probably something obvious that I'm just missing or misunderstanding. Thanks again!
<!DOCTYPE html>
<html>
<head>
<title>Marker Test</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
<?
// Generate JavaScript array initialization from database
$username="REDACTED";
$password="REDACTED";
$database="REDACTED";
$con=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$con) or die( "Unable to select database");
$query="SELECT * FROM pool where (record_id >= 1765) AND (record_id <= 1769)";
/*
$query="SELECT * FROM pool where (record_id <= '$marker_end') AND (record_id >= '$marker_start')";
$query="SELECT * FROM pool where session = '$session'";
*/
$result=mysql_query($query,$con);
$length=mysql_num_rows($result);
$length_count=1;
if ($result) {
echo "var PreviousClicks = [\n";
while($row = mysql_fetch_array($result)) {
$_lat=$row['google_lat'];
$_lng=$row['google_lng'];
$_record_id=$row['record_id'];
echo "{\n";
echo "lat: $_lat,\n";
echo "lng: $_lng,\n";
echo "title: \"$_record_id\"\n";
echo "}";
if($length_count<$length) {echo ",\n";} else {echo "\n";}
$length_count++;
} // end while
echo "];";
} // end if
mysql_close();
?>
</script>
<script type="text/javascript">
var map;
var markers = [];
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
title: "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} //end addMarker function
function initialize() {
// currently manual center initialization
var startLoc = new google.maps.LatLng(33.037380,-117.090431);
var mapOptions = {
zoom: 16,
center: startLoc,
mapTypeId: google.maps.MapTypeId.TRAFFIC
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// show prev clicks in database ------------------------------------------------------------------
for (i = 0; i < PreviousClicks.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng),
title: PreviousClicks[i].title,
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
} // end for
// end "show prev clicks in database" section ----------------------------------------------------
} // end function initialize
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas">
</div>
</body>
</html>
Inside a marker's event handler, this refers back to the marker. Therefore :
this.setMap(null);
will remove the marker from the map.
But more can be done with this code. In particular :
Avoid repeating code by using addMarker() to add both new and previous markers.
When markers are removed, also remove them from the markers array.
Both can be achieved as follows :
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
title: event.title || "A",
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
this.setMap(null);
//Remove the marker from the markers array.
for(i=0; i<markers.length; i++) {
if(markers[i] == this) {
removed = markers.splice(i, 1);
break;
}
}
});
markers.push(marker);
}
function initialize() {
...
google.maps.event.addListener(map, 'click', addMarker);
...
for (i = 0; i < PreviousClicks.length; i++) {
addMarker({
latLng: new google.maps.LatLng(PreviousClicks[i].lat, PreviousClicks[i].lng);
title: PreviousClicks[i].title
});
}
}
I have been trying to implement markerclusterer into my website for the past few weeks and everything I have tried has failed. I have no experience with code at all so everything I've been doing is trial and error.
The website I'm trying to add markerclusterer to is rfmaps.com.au.
I'm unsure as to what I'm doing wrong, and what needs to be fixed and really just need some good advice and help.
Here is the html code that I've been trying to get working. This code is simply all the bits and pieces I've been able to find from forums, all stuck together, and slightly edited (what I could figure out from help from forums)
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
var layerl0;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-25, 133),
zoom: 5,
mapTypeId: google.maps.MapTypeId.HYBRID
});
for (var i = 0; i < 1000; ++i) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude)
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
markers.push(marker);
}
var map = new google.maps.Map(document.getElementById("map"), options);
var mc = new MarkerClusterer(map);
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col2'",
from: '1UxncvVQSGcSvuN3t686sNuDQUsn8vQ6mws3zsvk'
},
map: map,
styleId: 4,
templateId: 1
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col2'",
from: '1UxncvVQSGcSvuN3t686sNuDQUsn8vQ6mws3zsvk',
where: "'Location' CONTAINS IGNORING CASE '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<label>Location</label><input type="text" id="search-string-l0">
<input type="button" onClick="changeMapl0()" value="Search">
</div>
</body>
</html>
I think you have not added the 'map' object while creating the markers inside the map.
This is your code:
var marker = new google.maps.Marker({
position: latLng,
draggable: true,
icon: markerImage
});
Please add map: map while generating your markers, like this:
var marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true,
icon: markerImage
});
Regarding marker cluster you need to add this js file- markerclusterer.js
markerCluster = new MarkerClusterer(map, marker);
I'm trying to load markers on the click of a button, but somewhere i'm missing something. 1. map pulls out and loads with one button click. 2. markers load with the click of a different button. here's what i have:
<!DOCTYPE>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="stylesheet" type="text/css" href="
<?php
$stylesarray = array("field");
echo $stylesarray[mt_rand(0,count($stylesarray)-1)];
?>.css">
<link rel="shortcut icon" href="images/favicon.ico">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=xxx&sensor=false"></script>
<script type="text/javascript">
var map = null;
$(document).ready(function(){
var lat=document.getElementById("latitude");
var long=document.getElementById("longitude");
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
lat.value=+position.coords.latitude;
long.value=+position.coords.longitude;
}
});
function load() {
var map = new google.maps.Map(document.getElementById("mapcontainer"), {
center: new google.maps.LatLng(20,0),
zoom: 3,
styles: mapstyle,
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
maxZoom: 8,
minZoom: 3,
mapTypeId: 'roadmap'
});
}
function getmarkers(){
downloadUrl("markers.php", function(data) {
//alert ("it works");
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var info = markers[i].getAttribute("info");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var date = markers[i].getAttribute("date");
var html = "<div id='tooltip'><div id='tiptext'>" + info
+ "<div id='number'>" + id + "</div>"
+ "<div id='date'>" + date + "</div>"
+ "</div></div>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
</script>
</head>
<body>
<div id="mapcontainer">
<form>
<input type="button" id="map" onClick="load()"></input>
</form>
<form>
<input type="button" onClick="getmarkers()"></input>
</form>
</body>
</html>
xml sample:
<markers>
<marker id="330" info="blahblah" date="2012-10-03" latitude="20.00" longitude="-81.00"/>
</markers>
Your map variable is local to your initialize function. It won't be accessible to the code that loads the markers.
Try defining it globally (outside of any functions):
var map = null;
Then initialize it in your load function
function load() {
map = new google.maps.Map(document.getElementById("mapcontainer"), {
The problem (after syntax errors) with your posted code is that the getmarkers function is local to the load function. It needs to be global to be called by an HTML element click function.
Live working version based off your example code
It seems like you do not declare the map variable in the global scope. Only in the load function scope, declare it as a global variable and it should work.
var map = null; // Declaring map in the global scope
function load() {
// map references to global scope
map = new google.maps.Map(document.getElementById("mapcontainer"), {
...
}
downloadUrl("markerinfo.php", function(data) {
...
var marker = new google.maps.Marker({
map: map, // map references to global scope
position: point,
icon: 'images/mapicon.png'
});
createTooltip(marker, html);
}
});
Try wrapping the DownloadUrl function call in another function and call that instead.
<input type="button" id="markerload" onClick="getMarkers()"></input>
function getMarkers() {
downloadUrl("markerinfo.php", function(data) {
...
});
}
function getmarkers() is designed to retrieve all markers with a for loop
for (var i = 0; i < markers.length; i++) {
To load one marker at a time you will need to increment it for each button click
Ie Var i =0 globally
Increment i at end of getmarkers() i++
You should stop the increments after the last member of array when it gets to markers.length
I would use MarkerManager to group neighboring marker in one, I tested an example but it does not work. Different markers are displayed well, but they are not together when they should. The manager is not working as it should, I do not understand why.
<html>
<head>
<title>Test GMap - MarkerManager</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/src/markermanager.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer_compiled.js"></script>
</head>
<body>
<div id="my-map" style="width:100%;height:700px"></div>
<script>
var maCarte = '';
function initialisation(){
var centreCarte = new google.maps.LatLng(47.389982, 0.688877);
var optionsCarte = {
zoom: 5,
center: centreCarte,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
maCarte = new google.maps.Map(document.getElementById("my-map"), optionsCarte);
// Create a new instance of the MarkerManager
var mgr = new MarkerManager(maCarte);
google.maps.event.addListener(mgr, 'loaded', function() {
console.log('loaded Map');
// Create marker array
var markers = [];
// Loop to create markers and adding them to the MarkerManager
for(var i = 0; i < 50; i += 0.1) {
var marker = new google.maps.Marker({position: new google.maps.LatLng(47.389982 + i, 0.688877 + i)});
markers.push(marker);
}
//var markerCluster = new MarkerClusterer(map, markers);
// Add the array to the MarkerManager
mgr.addMarkers(markers, 8);
// Refresh the MarkerManager to make the markers appear on the map
mgr.refresh();
});
}
google.maps.event.addDomListener(window, 'load', initialisation);
</script>
</body>
Can someone help me?
thank you very much
Your page works for me, but the markers are not immediately visible when the page loads. This is because of the zoom setting you have on line 34:
mgr.addMarkers(markers, 8);
if you set that to a lower number (say, 4) the markers will be visible when zoomed further out.