I am trying to follow this tutorial to create a circle upon map on click event. Here is the initialization of the map under tab1.js:
function initMap() {
forecastmap = new google.maps.Map(document.getElementById('forecastmap'), {
center: {lat: 1.352083, lng: 103.81983600000001},
zoom: 11
});
forecastmap.addListener('click', function(e) {
createBuffer(e.latLng, forecastmap);
});
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
}
Then inside my tab2.js where I perform all the logic to add the markers:
function createBuffer(coord, forecastmap) {
console.log('come in');
var marker = new google.maps.Marker({
position: coord,
map: forecastmap
});
clusterData.push(marker);
marker = new google.maps.Circle({
center: coord,
map: forecastmap,
strokeColor: '#000',
strokeWeight: 2,
strokeOpacity: 0.5,
fillColor: '#f0f0f0',
fillOpacity: 0.5,
radius: 20 * 1000
});
clusterData.push(marker);
}
I inserted a dummy message to check if the click event is registered. However, the message did not even printed out. I wonder which part of the code was wrong.
My HTML div:
<div class="box-body">
<div id="forecastmap" style="width:100%;height:350px" onclick="initMap();"></div>
</div>
Thanks!
Note that addListener is not a valid method, and you're either looking for the native addEventListener(), or Google's addDomListener().
I'm not too familiar with Google Maps, but considering the map is generated dynamically, the forecastmap variable may not available on page load. As such, you'll need to hoist the scope to an element that is available on page load, and make use of event delegation.
Instead of:
forecastmap.addListener('click', function(e) {
createBuffer(e.latLng, forecastmap);
});
You probably need something like:
document.getElementsByTagName('body')[0].addEventListener("click", function(e) {
// Check that the click target is #forecastmap
if (e.target && e.target.id == "forecastmap") {
createBuffer(e.latLng, forecastmap);
}
});
Hope this helps! :)
You have a click listener on the map div (the div with id="forecastmap"), that calls the initMap() function (onclick="initMap()"), recreating the map, losing any circle you may have added. If I remove that, and add a google.maps.event.addDomListenerOnce(document.getElementById("forecastmap"), ... that initialized the map on the first click (only), then I get markers and circles.
proof of concept fiddle
code snippet:
var forecastmap;
function initMap() {
forecastmap = new google.maps.Map(document.getElementById('forecastmap'), {
center: {
lat: 1.352083,
lng: 103.81983600000001
},
zoom: 11
});
forecastmap.addListener('click', function(e) {
createBuffer(e.latLng, forecastmap);
});
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
}
// google.maps.event.addDomListener(window, 'load', function() {
google.maps.event.addDomListenerOnce(document.getElementById('forecastmap'), "click", initMap);
// });
function createBuffer(coord, forecastmap) {
console.log('come in');
var marker = new google.maps.Marker({
position: coord,
map: forecastmap
});
// clusterData.push(marker);
marker = new google.maps.Circle({
center: coord,
map: forecastmap,
strokeColor: '#000',
strokeWeight: 2,
strokeOpacity: 0.5,
fillColor: '#f0f0f0',
fillOpacity: 0.5,
radius: 20 * 1000
});
// clusterData.push(marker);
}
html,
body,
#forecastmap {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class="box-body">
<div id="forecastmap" style="width:100%;height:350px"></div>
</div>
Related
Could someone help me with this code?
In my Rails project (I don't think it matters what project it is) I have a header that is fixed in position, called 'fixed_header'. There are links on this page, which load new pages underneath, when clicked.
One of the pages which loads, when clicked, has a div called 'map_canvas'. I want the code in my 'fixed_header' page to check for the existence of a div called 'map_canvas', and then, if it is there, load a map into it.
My code below is taken from snippets throughout my application, which work, but I can't make it work for this particular thing. Any help would be appreciated.
<script>
//Is 'ready' the code to use? This code is in 'fixed_header'
//My idea is that, once
//a link in 'fixed_header' is clicked, a new page loads
//underneath the header. The div 'map_canvas' is
//searched for and the function activates if it is found.
$(document).on("ready", function () {
if ($("#map_canvas").length > 0) {
initialize_google_maps();
}
});
function initialize_google_maps() {
var currentlatlng = new google.maps.LatLng(user_latitude, user_longitude);
var zoom = 10;
var myOptions = {
zoom: zoom,
center: currentlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: currentlatlng,
icon: {
oppacity: 0
}
});
var circle = new google.maps.Circle({
map: map,
fillOpacity: 0,
strokeWeight: 2,
strokeOpacity: 0.7,
radius: 10000,
});
circle.bindTo('center', marker, 'position');
}
</script>
Because you want to check the div existence in real time when user clicks on link the you should change your code
$(document).on("ready", function () {
if ($("#map_canvas").length > 0) {
initialize_google_maps();
}
});
as below
$('a').live('click',function() {
if ($("#map_canvas").length > 0) {
initialize_google_maps();
}
}
use the anchor selector according to your link classes or ids.
I am having trouble with my Google Maps web app, i am trying to add markers to a map and then when the user clicks on that marker, the name of marker appears.
I store information about each marker in an array like so:
var citymap = {};
citymap['edinburgh'] = {
center: new google.maps.LatLng(55.934120, -3.226569),
population: 284,
image:clueImage,
color: '#ff0000',
elementId:'clue1'
};
citymap['clue2'] = {
center: new google.maps.LatLng(55.970783, -3.164594),
population: 284,
image:clueImage,
color: '#ff0000',
elementId:'clue2'
}
citymap['clue4'] = {
center: new google.maps.LatLng(55.939583, -3.202092),
population: 284,
image:clueImage,
color: '#ff0000',
elementId:'clue3'
}
citymap['clue9'] = {
center: new google.maps.LatLng(0, 0),
population: 284,
image:clueImage,
color: '#ff0000',
elementId:'clue1'
}
I then loop through the array and add the marker to the map:
for (var city in citymap) {
var playerMarker = new google.maps.Marker({
position: citymap[city].center,
map: map,
icon: citymap[city].image
});
google.maps.event.addListener(playerMarker, "click", function() {
var elementConnected = citymap[city].elementId;
console.log(elementConnected);
});
}
Everything works as intended, however when I click on any of the markers, they all log the value of the last marker in the array. I know this is because thats where the loop finished, but I can not think of a way of making this work.
Help would be very helpful!
I think this is the universal "closure" problem in Javascript that people have. Someone might give a better way of doing this, but I think you need something like this:
google.maps.event.addListener(playerMarker, "click", (function() {
return function () {
var elementConnected = citymap[city].elementId;
console.log(elementConnected);
};
})(city));
Or if possible, depending on what else you're doing inside the click event, maybe this:
google.maps.event.addListener(playerMarker, "click", (function(elementId) {
return function () {
var elementConnected = elementId;
console.log(elementConnected);
};
})(citymap[city].elementId));
I just want to load the Google Maps based on the Mouseover event of different div element. For doing this I just used the following simple code. This code itself not working, can someone tell me what mistake I have made?
<script type="text/javascript">
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(40.740, -74.18),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var content = '<strong>A info window!</strong><br/>That is bound to a marker';
var infowindow = new google.maps.InfoWindow({
content: content
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
draggable: true
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener($("#showmap"), 'mouseover', function(){ alert("Hi");});
</script>
<div id='showmap'>
Show Map
</div>
<div id="map-canvas" style="width: 500px; height: 400px"></div>
Above simple alert function itself not called for this simple code.
The selector returns the jQuery object and the needed element can be accessed directly from the element array with a [0] . Also, make it "addDomListenerOnce", only need to initialize once.
$("#showmap")[0]
see a demo
google.maps.event.addDomListenerOnce($("#showmap")[0], 'mouseover',
function(){ initialize(); });
I just tried using this and this also worked.
Java Script Code:
function initialize(lat,longit,content) {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(lat, longit),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({
content: content
});
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
draggable: false
});
infowindow.open(map, marker);
}
Html Code:
<div id='showmap' onclick="initialize(1.37422,103.945,'<h2>Tampines</h2>')">
Show Map
</div>
I just tried using an idea from java, can we try a method call from the onclick and check whether it is working and to my surprise it worked.
I'm creating a map in Google Maps that I want to have only one marker. When the user clicks on the map for the first time, a marker would be created (with a circle around it). When the user clicks again, the old marker (and circle) is shifted to the new location.
So basically, this would be done by either moving the marker and circle, or by deleting them and creating a new marker and circle.
At the moment I'm trying to use the latter method, but unfortunately it's not working. Could anyone help?
<script>
//Initial variables (map and the markers array, which we're going to try to get rid of)
var map;
var markersArray = [];
//and GO!
function initialize()
{
//need to correct our starting location - over UK would be nice
var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
var mapOptions =
{
zoom: 12,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
//listen out for clicks and, when clicked, add a marker
google.maps.event.addListener(map, 'click', function(event)
{
addMarker(event.latLng);
});
}
// Add a marker to the map and push to the array.
function addMarker(location)
{
markersArray = [];
setAllMap(null);
var marker = new google.maps.Marker(
{
position: location,
map: map,
draggable: true
});
//create a circle
var circle = new google.maps.Circle(
{
map: map,
radius: 3000
});
//bind the circle to the marker we've also just created
circle.bindTo('center', marker, 'position');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
If you only want one marker at a time you do not need an array to store markers. You have to make sure you clear the map property of the marker and the circle using the setMap method and passing null. The circle is wrong, you do not have all the options you need and there is no bindTo method. Here is the circle documentation.
I saw that you set the marker's draggable propery to true so you also need to add a dragend event on the marker to relocate the circle to the markers new position using the setCenter method on the circle.
here is a complete example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Google Maps</title>
<style>
#map_canvas{
height:800px;
width:800px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script>
var marker, myCircle, map;
function initialize() {
var myLatlng = new google.maps.LatLng(37.7699298, -122.4469157);
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event){
addMarker(event.latLng);
});
}
function addMarker(latLng){
//clear the previous marker and circle.
if(marker != null){
marker.setMap(null);
myCircle.setMap(null);
}
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable:true
});
//circle options.
var circleOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: latLng,
radius: 3000
};
//create circle
myCircle = new google.maps.Circle(circleOptions);
//when marker has completed the drag event
//recenter the circle on the marker.
google.maps.event.addListener(marker, 'dragend', function(){
myCircle.setCenter(this.position);
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
i tried to built up a little Google Maps api in PHP which fetches Circles and Infowindows from a Database.
Anything works besides closing an InfoWindow after opening it.
The Chrome Developer console throws out the following errors:
GET http://maps.googleapis.com/maps/api/js/StaticMapService.GetMapImage?1m2&1i151368577549307460&2i99567197161272770&2e2&3u50&4m2&1u512&2u496&5m3&1e2&2b1&5sde-DE&token=119415 404 (Not Found) main.js:33 <- Onload
And on clicking on the Red popup it shows the following error:
Uncaught TypeError: Object # has no method 'O'
Tried to figure out a solution for hours now, hope you can help me!
Thank you!
<script type='text/javascript'>
var _infoWindow = new Array();var _marker = new Array();
function initialize() {
var mapOptions = {
zoom: 50,
center: new google.maps.LatLng(48.52039, 9.05949),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circles = [{"color":"fff","center":new google.maps.LatLng(48.5204, 9.05949),"radius":200}];
for(var circle in circles) {
new google.maps.Circle({
strokeColor: circles[circle].color,
strokeOpacity: 1,
strokeWeight: 2,
fillColor: circles[circle].color,
fillOpacity: 0.35,
map: map,
center: circles[circle].center,
radius: circles[circle].radius
});
}
var infoWindows = [{"center":new google.maps.LatLng(48.5204, 9.05949),"content":"<h2>Juhu!<\/h2>Html<br>Content <b>erlaubt<\/b>!"}];
var i = 0;
for(var infoWindow in infoWindows) {
_infoWindow[i] = new google.maps.InfoWindow({
content: infoWindows[infoWindow].content
});
_marker[i] = new google.maps.Marker({
position: infoWindows[infoWindow].center,
map: map,
title:'Test'
});
google.maps.event.addListener(_marker[i], 'click', new Function('_infoWindow['+i+'].open(map,_marker['+i+']);'));
i++;
}
}
window.onload = function(){
initialize();
}
</script>
</head>
<body>
<div id='map' style='height:500px;width:500px;'></div>
</body>
You are defining the map-variable inside a local scope(initialize), it will not be accessible inside the click-handler.
Add this to the top of the scripts:
var map;
And remove the var-keyword from this line:
var map = new google.maps.Map(document.getElementById('map'), mapOptions);