I am developing a Google map application in Qt that tracks user position and plots markers and connects the markers with polylines. After sometimes the page shows a white screen. I am using Qt 5.12.11 and Windows 10.
Observations:
When the markers were added to the map, the web engine memory keeps increasing.
Crash: When the white screen shows, the web engine is not running.
Here is the sample code.
webViewOnQml.pro
QT += quick webengine
CONFIG += c++11 qml_debug
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp
RESOURCES += qml.qrc
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtWebEngine/QtWebEngine>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
QGuiApplication app(argc, argv);
QtWebEngine::initialize();
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/res/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
main.qml
import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.0
import QtWebChannel 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Google Map")
WebEngineView {
id: view
anchors.fill: parent
url: "googleMaps.html"
}
}
googleMaps.html
<!-- Make sure to enter a valid Google Key in the Google Script at the bottom of this page -->
<!-- Visit https://developers.google.com/maps/documentation/javascript/get-api-key -->
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; width:100%; margin:0; padding:0; }
</style>
</head>
<body>
<button onclick="findLocation(-22.834418, 14.862920)">click</button>
<div id="map"></div>
<script>
var markersArray = [];
setTimeout(() => {
let mapUrl = document.createElement("script");
let url = "https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&v=3&callback=initMap"
mapUrl.setAttribute("src", url);
mapUrl.setAttribute("async","true");
mapUrl.setAttribute("defer", "defer");
document.body.appendChild(mapUrl);
}, 50);
function initMap() {
myPosition = new google.maps.LatLng(0,0)
map = new google.maps.Map(document.getElementById('map'), {
center:myPosition,
streetViewControl: false,
draggable: true,
scrollwheel: true,
panControl: true,
zoom: 17,
mapTypeId: 'satellite',
disableDefaultUI: true,
zoomControl:true,
mapTypeControl:true,
rotateControl: true,
tilt:0
})
dotIcon = { type:'Symbol',
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: '#196ffa',
strokeColor: '#196ffa',
fillOpacity: 1.0,
strokeWeight: 0.5,
zIndex:99,
}
latestDotIcon = { type:'Symbol',
path: google.maps.SymbolPath.CIRCLE,
scale: 3,
fillColor: '#10ff03',
strokeColor: '#10ff03',
fillOpacity: 1.0,
strokeWeight: 2
}
addLine();
currentMarker = new google.maps.Marker({
position:new google.maps.LatLng(0,0),
icon:latestDotIcon,
zIndex:99,
map: map
});
}
function addLine() {
poly = new google.maps.Polyline({
strokeColor: "#000dff",
strokeOpacity: 1.0,
strokeWeight: 1,
zIndex:99,
});
poly.setMap(map);
}
function findLocation(latitude,longitude){
let latLngVal = new google.maps.LatLng(latitude,longitude);
marker = new google.maps.Marker({
position: latLngVal,
icon:dotIcon,
map: map
});
marker.setMap(map);
map.setCenter(marker.getPosition());
path = poly.getPath();
path.push(latLngVal);
changeLocation(latitude,longitude);
currentMarker.setPosition(latLngVal);
delete latLngVal;
delete marker;
}
function changeLocation(latitude,longitude){
var lat = latitude+.01
var lon = longitude+.01
if(lat>=90) {
lat=-90
}
if(lon>=180) {
lon=-180
}
setTimeout(() => { findLocation(lat,lon); }, 200);
}
</script>
</body>
</html>
Note:- Replace your Google maps API key in "<YOUR_API_KEY>" in googleMaps.html to run the code.
Did I miss anything to configure?
How do avoid the crash and memory leak in the Qt Web engine?
Related
I have a 5 meter circle on google map, I would like by default it's invisible, when mouse hover to that 5 meters area, then make the cycle visible.
I tried myCircle.setVisible(false);, but after that, mouse event could not be triggered, so I am not sure how to handle it.
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
const radius = 5; // meters
const myCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0,
map: map,
center: map.getCenter(),
radius: radius,
});
var visible = false
myCircle.setVisible(visible);
myCircle.addListener('mouseover', function() {
console.log("mouseover")
visible = !visible
myCircle.setVisible(visible);
});
myCircle.addListener('mouseout', function() {
console.log("mouseout")
visible = !visible
myCircle.setVisible(visible);
});
map.fitBounds(myCircle.getBounds())
}
window.initMap = initMap;
To make a circle not visible, but still respond to mouse events, set the strokeWeight and the fillOpacity to 0. As you indicated in your comment, if you set the circle to visible:false, the mouse events don't work.
const myCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 0, // set to 0
fillColor: "#FF0000",
fillOpacity: 0.0, // set to 0
map: map,
center: map.getCenter(),
radius: radius,
});
Then on the mouseover event, set the strokeWeight and fillOpacity to your desired values, set them back to zero on mouseout:
myCircle.addListener("mouseover", function(evt) {
this.setOptions({
strokeWeight:2,
fillOpacity: 0.35
});
});
myCircle.addListener("mouseout", function(evt) {
this.setOptions({
strokeWeight:0,
fillOpacity: 0.0
});
})
proof of concept fiddle
code snippet:
/**
* #license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
const radius = 5; // meters
const myCircle = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 0,
fillColor: "#FF0000",
fillOpacity: 0.0,
map: map,
center: map.getCenter(),
radius: radius,
});
myCircle.addListener("mouseover", function(evt) {
this.setOptions({
strokeWeight:2,
fillOpacity: 0.35
});
});
myCircle.addListener("mouseout", function(evt) {
this.setOptions({
strokeWeight:0,
fillOpacity: 0.0
});
})
map.fitBounds(myCircle.getBounds())
}
window.initMap = initMap;
/**
* #license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/*
* 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;
}
<!DOCTYPE html>
<!--
#license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
<html>
<head>
<title>Simple Map</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>
<!--
The `defer` attribute causes the callback to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises
with https://www.npmjs.com/package/#googlemaps/js-api-loader.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly"
defer
></script>
</body>
</html>
I would like to display a polyline so that the vertices can not be moved, deleted or added, ie exactly like when the editable attribute is set to false, but the circles which are present when the editable attribute is set to true are still visible so that they can be clicked and a vertex number obtained.
So the polyline code could be:
newPoly = new google.maps.Polyline({
strokeColor: '#08088a',
strokeWeight: 2,
editable: false
});
Is this possible?
One option: process through the polyline, add circular markers to each vertex in the line with the vertex number in the marker's infowindow.
Related question: Google Maps V3 Polyline : make it editable without center point(s)
proof of concept fiddle
code snippet:
function initialize() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polyCoord = [
new google.maps.LatLng(41.86, 8.73),
new google.maps.LatLng(41.88, 8.75),
new google.maps.LatLng(42, 8),
new google.maps.LatLng(43.5, 9)
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < polyCoord.length; i++) {
bounds.extend(polyCoord[i]);
var marker = new google.maps.Marker({
position: polyCoord[i],
title: '#0',
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: 'white',
fillOpacity: 1,
scale: 3,
strokeColor: 'black',
strokeWeight: 1,
strokeOpacity: 1,
// anchor: new google.maps.Point(200, 200)
}
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("vertex #" + i + "<br>coord: (" + this.getPosition().toUrlValue(6) + ")");
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
// Polyline
var newPoly = new google.maps.Polyline({
strokeColor: '#08088a',
strokeWeight: 2,
editable: false,
path: polyCoord,
map: map
});
}
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"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
If you use Google Maps API v3.16 and later, polyline are not drawn when a new marker is added to the polyline path and MVCArray, only markers plotted on a map.
My program based on code from http://nettique.free.fr/gmap/toolbar.html
html file :
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>map toolbar implementation</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.exp&sensor=true"></script>
<style type="text/css">
--- truncate ----
</style>
<script type="text/javascript" src="toolbarv3_files/mapToolbar.js"></script>
<script type="text/javascript">
// Register an event listener to fire when the page finishes loading.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
body section
drawing toolbar :
<div id="hand_b" onclick="MapToolbar.stopEditing()"/>
<div id="line_b" onclick="MapToolbar.initFeature('line')"/>
canvas :
<div id="map" style="width: 85%; height: 100%; position: absolute;"></div>
script file (mapToolbar.js):
var map;
var MapToolbar = {
//reorder index of a poly markers array
reindex:function(markers){
markers.forEach(function(marker, index){
marker.index = index;
});
},
//add a point to a poly, 'e' can be a click event or a latLng object
addPoint : function(e, poly, index) {
var e = (typeof e.latLng != "undefined")? e.latLng : e,
image = new google.maps.MarkerImage('images/marker-edition.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
imageover = new google.maps.MarkerImage('images/marker-edition-over.png',
new google.maps.Size(9, 9),
new google.maps.Point(0, 0),
new google.maps.Point(5, 5)),
path = poly.getPath(),
index = (typeof index != "undefined")? index : path.length,
markers = (poly.markers)? poly.markers : new google.maps.MVCArray,
marker = new google.maps.Marker({
position: e,
map: map,
draggable: true,
icon: image
});
marker.index = index;
path.insertAt(index, e);
markers.insertAt(index, marker)
if(arguments[2]){
MapToolbar.reindex(markers);
}
features:{
.....
lineTab: {},
.....
},
//instanciate a new Feature instance and create a reference
initFeature: function(type){
new MapToolbar.Feature(type);
},
//check if a toolbar button is selected
isSelected: function(el){
return (el.className == "selected");
},
//the map DOM node container
....
lineCounter:0,
....
//select hand button
stopEditing: function() {
this.removeClickEvent();
this.select("hand_b");
},
//create new polyline function
MapToolbar.Feature.prototype.poly = function(type) {
var color = MapToolbar.getColor(false),
path = new google.maps.MVCArray,
poly,
self = this,
el = type + "_b";
if(type=="shape"){
poly = self.createShape( {strokeWeight: 3, fillColor: color}, path );
}else if(type=="line"){
poly = self.createLine( {strokeWeight: 3, strokeColor: color }, path );
}
poly.markers = new google.maps.MVCArray;
if(MapToolbar.isSelected(document.getElementById(el))) return;
MapToolbar.select(el);
MapToolbar.currentFeature = poly;
poly.setMap(map);
if(!poly.$el){
++MapToolbar[type+"Counter"];
poly.id = type + '_'+ MapToolbar[type+"Counter"];
poly.$el = MapToolbar.addFeatureEntry(poly.id, color);
MapToolbar.features[type+"Tab"][poly.id] = poly;
}
}
MapToolbar.Feature.prototype.createLine = function(opts, path) {
var poly = new google.maps.Polyline({
strokeWeight: opts.strokeWeight,
strokeColor: opts.strokeColor
}), self = this;
poly.setPath(new google.maps.MVCArray(path));
return poly;
}
//initialization function
function initialize(container) {
var options = {
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
map = new google.maps.Map(document.getElementById('map'));
map.setCenter(new google.maps.LatLng(47.9, 1.9 ));
map.setZoom(12);
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
with(MapToolbar){
with(buttons){
.....
$hand = document.getElementById("hand_b");
$line = document.getElementById("line_b");
....
}
....
select("hand_b");
}
MapToolbar.polyClickEvent = google.maps.event.addListener(map, 'click', function(event){
if( !MapToolbar.isSelected(MapToolbar.buttons.$shape) && !MapToolbar.isSelected(MapToolbar.buttons.$line) ) return;
if(MapToolbar.currentFeature){
MapToolbar.addPoint(event, MapToolbar.currentFeature);
}
});
}
complete version of "mapToolbar.js" script file is also available at : https://code.google.com/p/js2shapefile/source/browse/trunk/lib/mapToolbar.js?r=2
an error occurred when executing line "path.insertAt(index, e);" (addPoint function).
TypeError: this.j[qd] is not a function
...his[gd](a,b)}};L.insertAt=function(a,b){this.j[qd](a,0,b);bg(this);S[n](this,"in...
{main,g...try}.js (line 26, col 1473)
I had the same problem. I've solved changing poly.setPath in createLine function.
MapToolbar.Feature.prototype.createLine = function(opts, path) {
var poly = new google.maps.Polyline({
strokeWeight: opts.strokeWeight,
strokeColor: opts.strokeColor
}), self = this;
// 27/08/2014 - This not work
//poly.setPath(new google.maps.MVCArray(path));
poly.setPath(path);
return poly;
}
I was wondering whether it is possible to use icon font icons (e.g. Font Awesome) as markers in Google Maps V3 to replace the default marker. To show/insert them in a HTML or PHP document the code for the marker would be:
<i class="icon-map-marker"></i>
I just had the same problem - decided to do a quick and dirty conversion and host on github.
https://github.com/nathan-muir/fontawesome-markers
You can manually include the JS file, or use npm install fontawesome-markers or bower install fontawesome-markers.
Just include the javascript file fontawesome-markers.min.js and you can use them like so:
new google.maps.Marker({
map: map,
icon: {
path: fontawesome.markers.EXCLAMATION,
scale: 0.5,
strokeWeight: 0.2,
strokeColor: 'black',
strokeOpacity: 1,
fillColor: '#f8ae5f',
fillOpacity: 0.7
},
clickable: false,
position: new google.maps.LatLng(lat, lng)
});
Edit (April-2016): There's now packages for v4.2 -> v4.6.1
I know this is an old post, but just in case you can use the MarkerLabel object now:
var marker = new google.maps.Marker({
position: location,
map: map,
label: {
fontFamily: 'Fontawesome',
text: '\uf299'
}
});
Worked for me.
.
Reference Google Maps Maker
Here's my attempt at the same thing (using "markerwithlabel" utility library) before I realised Nathan did the same more elegantly above: http://jsfiddle.net/f3xchecf/
function initialize() {
var myLatLng = new google.maps.LatLng( 50, 50 ),
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
marker = new MarkerWithLabel({
position: myLatLng,
draggable: true,
raiseOnDrag: true,
icon: ' ',
map: map,
labelContent: '<i class="fa fa-send fa-3x" style="color:rgba(153,102,102,0.8);"></i>',
labelAnchor: new google.maps.Point(22, 50)
});
marker.setMap( map );
}
initialize();
The light weight solution
fontawesome-markers: 480kb
markerwithlabel: 25kb
To avoid these dependencies, simple go to fontawesome-markers, find the path for the icon you want, and include it as follows:
var icon = {
path: "M27.648-41.399q0-3.816-2.7-6.516t-6.516-2.7-6.516 2.7-2.7 6.516 2.7 6.516 6.516 2.7 6.516-2.7 2.7-6.516zm9.216 0q0 3.924-1.188 6.444l-13.104 27.864q-.576 1.188-1.71 1.872t-2.43.684-2.43-.684-1.674-1.872l-13.14-27.864q-1.188-2.52-1.188-6.444 0-7.632 5.4-13.032t13.032-5.4 13.032 5.4 5.4 13.032z",
fillColor: '#E32831',
fillOpacity: 1,
strokeWeight: 0,
scale: 0.65
}
marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: icon
});
In a modern browser one can use the canvas in order to render the font to png, and then use the data URI scheme:
function getIcon(glyph, color) {
var canvas, ctx;
canvas = document.createElement('canvas');
canvas.width = canvas.height = 20;
ctx = canvas.getContext('2d');
if (color) {
ctx.strokeStyle = color;
}
ctx.font = '20px FontAwesome';
ctx.fillText(glyph, 0, 16);
return canvas.toDataURL();
}
For example: getIcon("\uf001") for the music note.
If you want the awesomefont MARKER with an awesomefont ICON INSIDE:
1. copy the SVG path of the awesomefont marker (click download and copy the SVG path) and use it as icon (remember to credit the authors, see license).
Then you can change it's color to anything you want.
2. As label you only insert the awesome font icon code and the color you want.
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<div id="map"></div>
<script>
function init() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(51.509865, -0.118092)
});
var icon = {
path: "M172.268 501.67C26.97 291.031 0 269.413 0 192 0 85.961 85.961 0 192 0s192 85.961 192 192c0 77.413-26.97 99.031-172.268 309.67-9.535 13.774-29.93 13.773-39.464 0z", //SVG path of awesomefont marker
fillColor: '#333333', //color of the marker
fillOpacity: 1,
strokeWeight: 0,
scale: 0.09, //size of the marker, careful! this scale also affects anchor and labelOrigin
anchor: new google.maps.Point(200,510), //position of the icon, careful! this is affected by scale
labelOrigin: new google.maps.Point(205,190) //position of the label, careful! this is affected by scale
}
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: icon,
label: {
fontFamily: "'Font Awesome 5 Free'",
text: '\uf0f9', //icon code
fontWeight: '900', //careful! some icons in FA5 only exist for specific font weights
color: '#FFFFFF', //color of the text inside marker
},
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
It is possible to import the svgs directly from #fortawesome/free-solid-svg-icons and use the Icon Interface.
import { faMapMarkerAlt } from "#fortawesome/free-solid-svg-icons";
function initMap(): void {
const center = { lat: 0, lng: 0 };
const map = new google.maps.Map(
document.getElementById("map") as HTMLElement,
{
zoom: 9,
center,
}
);
new google.maps.Marker({
position: { lat: 0, lng: 0 },
map,
icon: {
path: faMapMarkerAlt.icon[4] as string,
fillColor: "#0000ff",
fillOpacity: 1,
anchor: new google.maps.Point(
faMapMarkerAlt.icon[0] / 2, // width
faMapMarkerAlt.icon[1] // height
),
strokeWeight: 1,
strokeColor: "#ffffff",
scale: 0.075,
},
});
}
Can try it at: https://codesandbox.io/embed/github/googlemaps/js-samples/tree/sample-marker-modern
I've put together a simple JS library that generates nice SVG markers using the Font Awesome icons. https://github.com/jawj/MapMarkerAwesome
All I seen looks good, but they would not work for me; However, this worked smoothly and is small.
Use a link out to wherever your font awesome library is.
The normal marker javascript code is fine and add the icon attribute.
// The marker
var marker = new google.maps.Marker({
position: uluru,
icon: 'https://cdn.mapmarker.io/api/v1/pin?icon=fa-truck&size=50&hoffset=0&color=%23FFFFFF&background=%23FF7500&voffset=-1',
map: map,
});
}
You can change the font awesome icon, position, color, etc. right there in the icon: attribute.
I am trying to get the following behaviour. When I click the map I want a rectangle to start appearing. As a move the mouse (not drag) I want the rectangle to adjust itself to fit the first click and the mouse position.
When I click the mouse the second time, I want to capture the corner coordinates (for a spatial search query) and then have the rectangle stop resizing.
On the third mouse click I want the rectangle to disappear.
At the moment the rectangle appears and resizes but it never stops following the mouse.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#map { width: 750px; height: 500px; }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"/></script>
<script type="text/javascript">
var start = new google.maps.LatLng();
var clicked=0;
window.onload = function()
{
var settings = {
mapTypeId: google.maps.MapTypeId.TERRAIN, // map type
zoom: 8, // map type
center: new google.maps.LatLng(-33.890542, 151.274856) // coordinates
};
var map = new google.maps.Map(document.getElementById("map"), settings);
rectangle = new google.maps.Rectangle();
google.maps.event.addListener(map, 'click', function(event) {
loc = event.latLng;
if(clicked==0){
$("#start").html(loc.toString());
start=loc;
// start the rectangle
var rectOptions = {
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
};
rectangle.setOptions(rectOptions);
clicked=1;
}
else if(clicked==1){
$("#end").html(loc.toString());
clicked=2;
alert("clicked "+clicked);
}
else if(clicked==2){
$("#start").html("");
$("#dragged").html("");
$("#end").html("");
clicked=0;
}
});
google.maps.event.addListener(map, 'mousemove', function(event) {
if(clicked==1){
loc = event.latLng;
$("#dragged").html(loc.toString());
$("#dragged").html(loc.toString());
var bounds = new google.maps.LatLngBounds();
bounds.extend(start);
bounds.extend(loc);
rectangle.setBounds(bounds);
}
else if(clicked==2){
alert("mouseover: "+clicked);
rectangle.setMap(null);
}
});
};
</script>
</head>
<body>
<div id="map"></div>
</body>
I've just ran into the same problem and I just noticed how old this post is. Everyone that has this problem, you need to check out https://developers.google.com/maps/documentation/javascript/reference#DrawingManager
use that instead of google.maps.Rectangle(); Check This Out:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing"></script>
<script type="text/javascript">
function initialize() {
// render map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng( 36.175, -115.1363889 ),
mapTypeControl: false,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// get the DrawingManager - Remember to include &libraries=drawing in the API call
var draw = new google.maps.drawing.DrawingManager({
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
rectangleOptions: {
fillColor: '#990000',
fillOpacity: .4,
strokeWeight: 3,
strokeColor: '#999',
clickable: true,
editable: true,
zIndex: 1
}
});
// set the cursor to the rectangle
draw.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
// adds a listener for completed overlays, most work done in here
google.maps.event.addListener(draw, 'overlaycomplete', function(event) {
draw.setDrawingMode(null); // put the cursor back to the hand
if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
//do something
}
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
// do something
}
if (event.type == google.maps.drawing.OverlayType.RECTANGLE) {
// on click, unset the overlay, and switch the cursor back to rectangle
google.maps.event.addListener(event.overlay, 'click', function() {
this.setMap(null);
draw.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
});
}
});
// end of initialize
draw.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);