Is it possible to turn on drawing mode for an existing polyline with a google's DrawingManager?
It's possible in Google Maps web app when going to custom map editor (My Maps in menu -> Create map -> Draw). Then create a polyline, right-click on the last point and select extend line (see picture below).
But I can't find a way to do the same with google maps api v3.
set the editable-option of the polyline to true and add points to the polyline-path
Example:
click on the line makes the line editable
click on the map stops editing
rightclick on the vertex while extending the line stops editing
function initMap() {
var goo = google.maps,
map = new goo.Map(document.getElementById('map'), {}),
line = new goo.Polyline({
path: [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
]}),
bounds = new goo.LatLngBounds();
line.getPath().getArray().forEach(function(ll){
bounds.extend(ll);
});
map.fitBounds(bounds);
line.setMap(map);
/**
* click on the line makes the line editable
*
* click on the map stops editing
*
* rightclick on the vertex while extending the line stops editing
*
**/
goo.event.addListener(line,'click',function(e){
var line=this;
//make the line editable
this.setEditable(true);
//stopediting on map-click
goo.event.addListenerOnce(this.getMap(),'click',function(){
line.setEditable(false);
});
//when a vertex has been clicked
if(typeof e.vertex==='number'){
//when the first or last vertex has been clicked
if(!e.vertex ||e.vertex===this.getPath().getLength()-1){
//when the first vertex has been clicked reverse the path to
//be able do push a vertex
if(e.vertex===0){
var p=this.getPath().getArray();
p.reverse();
this.setPath(p);
}
//push a vertex
this.getPath().push(e.latLng)
//observe the mousemove of the map to set the latLng of the last vertex
var move=goo.event.addListener(this.getMap(),'mousemove',function(e){
line.getPath().setAt(line.getPath().getLength()-1,e.latLng)
});
//stop editing on rightclick
goo.event.addListenerOnce(this,'rightclick',function(){
goo.event.removeListener(move);
this.setEditable(false);
});
}
}
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3&callback=initMap"></script>
<div id="map"></div>
Related
i have problem implementing address visualization on markers within m google maps dynamic map.
My code is the following:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Marker Clustering</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>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 44.0, lng: 12.0}
});
// Create an array of alphabetical characters used to label the markers.
var labels = '';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 44.5153, lng: 11.3428},
{lat: 44.4926, lng: 11.3657},
{lat: 44.4948, lng: 11.3158}
//input geocode continue
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=initMap">
</script>
</body>
</html>
I want to add on click popup information on each marker, but i cannot manage to do it, i've searched a lot but I'ven't find any working solution.
Someone can help me?
i've edited your code to let it work with info window
before, initializing the markers add this line of code
var infoWin = new google.maps.InfoWindow();
this will initialize the info window, now modify your markers initialization to this
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
//// here we are adding the event listner for the markers to open the info window on click
google.maps.event.addListener(marker, 'click', function(evt) {
infoWin.setContent(location.info);
infoWin.open(map, marker);
})
return marker;
});
notice we are reading the info from the location array so change your locations array to include a third parameter "info" like this
var locations = [{
lat: 44.5153,
lng: 11.3428,
info: 'place 1'
}, {
lat: 44.4926,
lng: 11.3657,
info: 'place2'
}, {
lat: 44.4948,
lng: 11.3158,
info: 'place 3'
}
//input geocode continue
]
I have a Google Map inside a JavaScript Accordion UI, and it puts a pin in the passed latitude/longitude and "centers" on that pin.
For the first map, it works. When you click either of the other two, it seems to put the (base of the) pin in the top-left corner of the map. I'm already calling resize, as you can see in my code.
Here is a fiddle which demonstrates the issue: http://jsfiddle.net/myingling/1c4bjsff/2/
I'm sure this is something simple, but what am I missing?
You need to save the center of each map, then set it once the new accordion is activated (and that map has a size, when the map/accordion is hidden, it has a computed size of zero, so the marker is centered in the upper left hand corner of the div).
One option:
var maps = [];
jQuery("#accordion").accordion({
change: function(event, ui) {
for (var i = 0; i < maps.length; i++) {
google.maps.event.trigger(maps[i], 'resize');
maps[i].setCenter(maps[i]._center);
}
}
}).find('.map').each(function(i, o) {
var latLong = new google.maps.LatLng(
jQuery(this).data("lat"), jQuery(this).data("long"));
var map = new google.maps.Map(o, {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROAD,
center: latLong
});
maps.push(map);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title: jQuery(this).data('time')
});
google.maps.event.trigger(map, 'resize');
map.setCenter(latLong);
map._center = latLong;
jQuery(o).data('map', map);
});
proof of concept fiddle
I am trying to make an AJAX map Google map, where the place markers update but not the map.
I have an ajax setup with a settimeout function, which returns new javascript. When the new javascript is loaded into my HTML, the changes do not reflect on my google map.
When I go into the firefox inspector and try and manipulate the javascript, (to try and change marker GPS coordinates), nothing happens to the map, and the points are still the same. Why does that not affect the map?
I have looked at several links to try and help me, but none of them explain the logic behind the javascript.
My PHP script returns javascript in plain text. But when these get
added to the HTML, The google map does not change and looks like it
needs to be re initialized before it recognizes new javascript?
Can someone explain how I should update the javascript, so the map re-centers on the newest marker and places the newest marker without refreshing the page / re initializing the map?
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: -20.530637, lng: 46.450046}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
new google.maps.LatLng("-21.530637,46.450046),
new google.maps.LatLng("-22.530637,46.450046),
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'content.php',
type:'POST',
success:function(results) {
locations=results;
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,5000);
</script>
My "content.php" file. returns more google maps LatLng markers in plain text.
so PHP output is:
new google.maps.LatLng("-23.530637,46.450046"),
new google.maps.LatLng("-24.530637,46.450046"),
new google.maps.LatLng("-25.530637,46.450046"),
new google.maps.LatLng("-26.530637,46.450046")
I would like to summary the behavior of your ajax map:
Initialize map (probably with a set of predefined locations)
Repeatedly call content.php to retrieve new update of markers
Draw new markers to your map
The problem is that your code that handles ajax result doesn't do any map manipulation. In fact, it has to update the variable locations with new location set. Then create new markers with updated list of locations, then call MarkerCluster to apply them.
I created a fiddle to demonstrate it: https://jsfiddle.net/anhhnt/paffzadz/1/
What I did is extract the marker creating part from initMap, so that it can be called multiple times after locations is updated.
function updateMarker () {
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
};
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: -28.024, lng: 140.887}
});
updateMarker(map);
};
var locations = [
{lat: -31.563910, lng: 147.154312},
{lat: -33.718234, lng: 150.363181},
{lat: -33.727111, lng: 150.371124}
]
function refresh_div() {
jQuery.ajax({
url:'/echo/json/',
type:'POST',
data: {
json: JSON.stringify([
{lat: -42.735258, lng: 147.438000},
{lat: -43.999792, lng: 170.463352}
])
},
success:function(results) {
locations.concat(results);
updateMarker();
}
});
}
t = setInterval(refresh_div,5000);
Hope it helps.
Perhaps you have simple syntax error in your code - missing closing double quote:
new google.maps.LatLng("-23.530637,46.450046"),
...
..or better - remove first double quote:
new google.maps.LatLng(-23.530637,46.450046),
...
I'm using for a while following javascript code to load google map as DIV background.
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 15,
// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(54.549047, 18.443433), // New York
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [ { featureType:"all", elementType:"all", stylers:[ { invert_lightness:true }, { saturation:10 }, { lightness:30 }, { gamma:0.5 }, { hue:"#1C705B" } ] } ]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map');
// Create the Google Map using out element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
}
works perfectly. But when I've tried to load there a marker which will point to my location, it crashes. Any ideas what will be the proper placement of such? I assume this is the proper code (which doesn't work..):
var myLatlng = new google.maps.LatLng(54.549047, 18.443433);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
thanks for the help!
Wonder if anyone can help me, I have setup a google map all works nicely. The only thing I cant work out how to do is to open an info window based on ID from an external html link that's not in the JS.
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
infowindow = new google.maps.InfoWindow();
// Custom markers
var icon = "img/marker.png";
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ val:0, lat: -40.149049, lng: 172.033095, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
{ val:1, lat: -41.185765, lng: 174.827516, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
icon: icon,
id: data.val
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.html;
content.appendChild(title);
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(content);
infowindow.open(map, this);
map.setCenter(this.position);
console.log(this.id);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
}
<p id="1">link to open marker</p>
Any help would be gratefully appreciated
Richard :)
The Golden Goose
Then in your js have a function to open the infowindow (such as show()) which takes the properties from that link (opening id 7).
function show(id){
myid = id;
if(markers[myid]){
map.panTo(markers[myid].getPoint());
setTimeout('GEvent.trigger(markers[myid], "click")',500);
map.hideControls();
}
}
That's the function I used previously with one of the marker managers from v2. You have to make sure you set an id for each marker as you set it and then you can call it.
The one thing I made sure of (to simplify matters) was to make sure the map marker set/array was exactly the same as the sql result I used on the page. That way, using id's was a piece of cake.