I am struggling to get Google Maps to show me the data stored in a GeoJSON object. If I use a click event on the polygon it works first time. Code below:
// Get the GeoJSON file from the server
HTTP.get(Meteor.absoluteUrl("/geo.json"), function(err,result) {
GoogleMaps.maps.fibreMap.instance.data.loadGeoJson("/geo.json");
});
// Add style and colouring to the map
GoogleMaps.maps.fibreMap.instance.data.setStyle(function(feature) {
// Get the Fibrehood Status
var status = feature.getProperty('status');
// Add colour accoring to status
if (status == "live") {
opacity = 0.65;
} else if (status == "build") {
opacity = 0.4;
} else if (status == "register_i") {
opacity = 0.2;
}
// Return the correct styling
return ({
fillColor: '#ec008c',
strokeColor: '#ec008c',
strokeOpacity: 0.35,
strokeWeight: 0,
fillOpacity: opacity
});
});
GoogleMaps.maps.fibreMap.instance.data.addListener('click', function(event) {
var hood = event.feature.getProperty('name');
var status = event.feature.getProperty('status');
console.log(hood + " : " + status);
});
However, when trying to use GeoComplete to drop a pin on an address, it does not run. I know that this should be triggered with some sort of event, like a marker dropping on the map or a Dom Element changing, but I cannot figure it out.
Does anyone have any insight into how to trigger events from the DOM or dropping a marker onto the map? I am a bit of a noob and would really appreciate any help.
Thanks
Mike
Does anyone have any insight into how to trigger events from the DOM or dropping a marker onto the map?
Sure, there is. Google Maps JS API has a well-documented example of working with map events and map markers.
In this example a marker will drop on the map where you clicked using the 'click event'.
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng, map);
});
// Add a marker at the center of the map.
addMarker(bangalore, map);
}
// Adds a marker to the map.
function addMarker(location, map) {
// Add the marker at the clicked location, and add the next-available label
// from the array of alphabetical characters.
var marker = new google.maps.Marker({
position: location,
label: labels[labelIndex++ % labels.length],
map: map
});
}
Full demo is here.
Here's a link to a sample for Listening to DOM Events:
https://developers.google.com/maps/documentation/javascript/examples/event-domListener
Related
How do i change my center for google maps with a link and remove other markers? i have this code
https://jsfiddle.net/m9ugbc7h/
So, i need to create a link for example
Ventura
In this case the function must change google maps center to focus the "ventura" marker and hide the other markes and when the user clicks on
Dolphinaris
the zoom will change and will hide every other marker and show only the ones of Dolphinaris
Thanks in advance
Make map visible outside of jQuery(document).ready.
Create var markers = []; array.
When crating markers, add custom property name to it, and push marker into markers array:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(21.0241839, -86.8148164),
map: map,
visible: true,
icon: ventura,
name: 'ventura',
});
markers.push(marker);
On click, invoke resetMap() function:
Ventura
Inside resetMap function, set center and zoom to map, iterate markers, matching them by custom property name - matched one set visible, others set to invisible.
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
map.setCenter(newPos);
map.setZoom(zoom);
markers.forEach(function(marker) {
if(marker.get('name') == name)
{
console.log('match');
marker.setVisible(true);
}
else
{
marker.setVisible(false);
}
});
Working fiddle: https://jsfiddle.net/m9ugbc7h/1/
EDIT:
Question: "is there any way to change smoothly the zoom and coordinates?"
Yes, use method:
panTo(latLng:LatLng|LatLngLiteral)
Changes the center of the map to the given LatLng. If the change is
less than both the width and height of the map, the transition will be
smoothly animated.
https://developers.google.com/maps/documentation/javascript/reference?csw=1
EDIT 2:
Implementing panTo is easy:
map.panTo(newPos);
instead of:
map.centerTo(newPos);
but as I have faced a bit 'flickering' effect due to hide/show markers that are close on the map, I have added some delay in functions invocation + markers show/hide:
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
$.when( map.setZoom(zoom) ).done(function(){
$.when( map.panTo(newPos)).done(function(){
setMarkerVisibility(name);
});
});
}
And showing matched marker is now executed with 300 ms delay:
function setMarkerVisibility(name){
markers.forEach(function(marker) {
console.log(marker.get('name'));
if(marker.get('name') == name)
{
setTimeout(function(){ marker.setVisible(true); }, 300);
}
else
{
marker.setVisible(false);
}
});
}
It looks a bit smoother like this.
Working fiddle: https://jsfiddle.net/m9ugbc7h/3/
I have a map with several markers on it. I construct these markers with this piece of code:
var markers = {},
lbl = 'unique';
markers[lbl] = L.circleMarker(ll,
{ radius: 8,
fillColor: '#ff0000',
color: '#00ff00',
weight: 0,
opacity: 1,
fillOpacity: 0.9,
className: 'svgMarker'
})
.bindLabel('This is '+lbl)
.addTo(markerLayer)
.addTo(map)
.on('click', clickHandler);;
Within the clickHandler I want to load some stuff depending on which marker I clicked. To distinguish them, I have a lbl (label)var which holds the unique alphanumeric ID of the marker.
function clickHandler(event){
//- zoom to the marker
map.setView(ev.latlng, 16);
//- Load the marker dependent stuff.
// how can I pass the unique label to this function?
}
Is there a way to pass the unique id with the mouse event or is there an other way to give a 'property' to the marker which I can read out in the clickHandler?
just add a property to your marker (just javascript stuff) ... you can get it back with context 'this' in the event handler
var marker = L.marker([48.8588589,2.3470599]);
marker.id = 'unique_id';
marker.addTo(map);
marker.on('click', clickHandler);
function clickHandler(event) {
console.log(this.id);
}
I'm using google maps v3, and my issue is that I have 200+ polygons on one map, they are all editable, and I need to make an ajax call in the event listeners for change which use path instead of the polygon to detect the changes.
so in the callback function this = polygon.getPath(), how can I get the polygon that it belongs to. In the polygon I use set to set the info I require for the ajax call.
poly1.set('name', 'poly1');
poly1.set('id', 1);
google.maps.event.addListener(poly1, 'dragend', setNewArea);
google.maps.event.addListener(poly1.getPath(), 'insert_at', setNewArea);
google.maps.event.addListener(poly1.getPath(), 'remove_at', setNewArea);
google.maps.event.addListener(poly1.getPath(), 'set_at', setNewArea);
so in setNewArea, I can easily check this to see if it's the poly or the path, but if it's the path I have no way to get the parent poly for it. I don't want to have 200 custom callbacks just to hardcode the poly, there has to be an other cleaner way.
One way to do this is to add the object reference to poly1 to your assigned callback. Here is some code I wrote using the maps API that adds a listener for a click event on a specific marker that opens an info window.
var latLng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latLng,
map: window.map,
title: pinName
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(window.map, marker);
});
So for your example, you might want to do something like what's below. That will ensure that your callback function is getting a reference to the poly object, even if the triggering event is related to the path.
poly1.set('name', 'poly1');
poly1.set('id', 1);
google.maps.event.addListener(poly1, 'dragend', function() {
setNewArea(poly1);
});
google.maps.event.addListener(poly1.getPath(), 'insert_at', function() {
setNewArea(poly1);
});
You can make circular reference among objects.
var thePath = poly1.getPath();
thePath.parent = poly1;
google.maps.event.addListener(thePath, 'set_at', function () {
console.log('My parent is the polygon', this.parent);
}.bind(this);
I'm using Google Maps API and jquery-ui-maps (this questions has nothing to do with the plugin which is working great).
I've created a FusionTablesLayer with all countries except Mozambique. The user could place a marker and reposition it. I'm trying to find a way to block the drag (or alert the user, it doesn't matter now) if he tries to place the marker outside Mozambique (over the FusionTablesLayer).
After some research I discover this method: containsLocation(point:LatLng, polygon:Polygon), which computes whether the given point lies inside the specified polygon.
It should receive a Polygon and I've got a FusionTablesLayer. Any clue how to solve this?
Here's my code:FIDDLE
Try to place a marker and drag it...
//Initialize the map
var mapa = $('#map_canvas').gmap({'center': '-18.646245,35.815918'});
$('#map_canvas').gmap('option', 'zoom', 7);
//create the layer (all countries except Mozambique)
var world_geometry;
$('#map_canvas').gmap().bind('init', function(event, map) {
world_geometry = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1N2LBk4JHwWpOY4d9fobIn27lfnZ5MDy-NoqqRpk',
where: "ISO_2DIGIT NOT EQUAL TO 'MZ'"
},
styles: [{
polygonOptions: {
fillColor: "#333333",
fillOpacity: 0.3
}
}],
map: map,
suppressInfoWindows: true
});
});
$('#map_canvas').gmap().bind('init', function(event, map) {
$(map).click(function(event) {
$('#map_canvas').gmap('clear', 'markers');
$('#map_canvas').gmap('addMarker', {
'position': event.latLng,
'draggable': true,
'bounds': false
}, function(map, marker) {
}).dragend(function(event) {
//I need to check if the marker is over the FusionTablesLayer and block the drag.
//var test = google.maps.geometry.poly.containsLocation(event.latLng, world_geometry);
}).click(function() {
})
});
});
Since there is no containsLocation in FusionTablesLayer, and since no mouseevents but click is supported (that would have made it a lot easier) - there is no other way round than to check if there is being dragged outside the area itself, Mozambique - not into the FusionTablesLayer. The solution is to create an invisible polygon for Mozambique, and use that polygon to check for containsLocation when dragging is finished.
The polygon can be based on the KML from the row you are excluding, MZ. That can be done using google.visualization.Query.
1) include the Google API loader in your project :
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
2) initialize Visualization :
google.load('visualization', '1.0');
3) define a variable for the polygon holding the Mozambique borders :
var mozambique;
The following is a function that loads the geometry data for Mozambique, and then creates an invisible polygon on the map; google.visualization.Query is used instead of the automated FusionTablesLayer so we can extract the <coordinates> from the KML and use them as base for the polygon.
In basic, this is how to convert KML-data from a FusionTable to a polygon :
function initMozambique(map) {
//init the query string, select mozambique borders
var sql = encodeURIComponent("SELECT 'geometry' FROM 1N2LBk4JHwWpOY4d9fobIn27lfnZ5MDy-NoqqRpk WHERE ISO_2DIGIT ='MZ'");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
query.send(function (response) {
var data = response.getDataTable().getValue(0, 0);
//create a XML parser
if (window.DOMParser) {
var parser = new DOMParser();
var kml = parser.parseFromString(data, "text/xml");
} else { // Internet Explorer
var kml = new ActiveXObject("Microsoft.XMLDOM");
kml.loadXML(data);
}
//get the coordinates of Mozambique
var latLngs = kml.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue.split(' ');
//create an array of LatLngs
var mzLatLngs = [];
for (var i = 0; i < latLngs.length; i++) {
var latLng = latLngs[i].split(',');
//<coordinates> for this FusionTable comes in lng,lat format
mzLatLngs.push(new google.maps.LatLng(latLng[1], latLng[0]));
}
//initialize the mozambique polygon
mozambique = new google.maps.Polygon({
paths: mzLatLngs,
fillColor: 'transparent',
strokeColor : 'transparent',
map: map
});
//make the mozambique polygon "transparent" for clicks (pass clicks to map)
google.maps.event.addListener(mozambique, 'click', function(event) {
google.maps.event.trigger(map, 'click', event);
});
});
}
Call the above initMozambique function in your second gmap().bind('init'... :
$('#map_canvas').gmap().bind('init', function(event, map) {
initMozambique(map);
...
Now you can check the mozambique-polygon for containsLocation after dragging
...
}).dragend(function(event) {
if (!google.maps.geometry.poly.containsLocation(event.latLng, mozambique)) {
alert('You are not allowed to drag the marker outside Mozambique');
}
//I need to check if the marker is over the FusionTablesLayer and block the drag.
//var test = google.maps.geometry.poly.containsLocation(event.latLng, world_geometry);
}).click(function() {
})
...
See forked fiddle, working demo with the code above -> http://jsfiddle.net/yb5t6cw6/
Tested in Chrome, FF and IE, ubuntu and windows.
I am attempting to create a google map with markers on my page. I have an unordered list where each item has data attributes for latitude, longitude and title. Using JQuery I pull these values and produce a marker on the map for each item in the list. Everything seems to work OK except google maps will not load tiles as you pan around the map.
This is how I initialize the map:
var map;
// initialize google map
$(function () {
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(CoordinatesLat, CoordinatesLong),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
// initiate map
map = new google.maps.Map($("#map")[0], myOptions);
// when map is loaded, add events and behaviors to it
google.maps.event.addListenerOnce(map, 'tilesloaded', addEventsToMap(".event")); //commenting this line prevents GMAP problems
});
FYI - before I was using maps.event.addListener() and the map would work momentarily and then become completely unresponsive. Changing it to maps.event.addListenerOnce() stopped the freezing but still has the tile loading problem.
And this is the callback, where evidently I've done something wrong:
//add events from event list to map. add behavior to events ie. mouseover
function addEventsToMap(selector) {
$(selector).each(function (i, $e) {
$e = $($e);
var latlng;
if ($e.attr("data-geo-lat") && $e.attr("data-geo-long")) {
latlng = new google.maps.LatLng($e.attr("data-geo-lat"), $e.attr("data-geo-long"));
$e.marker = new google.maps.Marker({
position: latlng,
map: map,
title: $e.attr("data-title")
});
google.maps.event.addListener($e.marker, 'click', function () { window.location = $e.attr("data-href"); });
google.maps.event.addListener($e.marker, 'mouseover', function () { $e.addClass("event-hover"); });
google.maps.event.addListener($e.marker, 'mouseout', function () { $e.removeClass("event-hover"); });
//when mouse hovers over item in list, center map on it's marker
$e.mouseenter(function () {
map.panTo(latlng);
});
}
});
}
Any idea what could be causing this?
I see a problem, though I'm not sure if it's the issue here. If you examine this line:
google.maps.event.addListenerOnce(map, 'tilesloaded', addEventsToMap(".event"));
What you are intending to do is call your 'addEventsToMap' once the map is loaded, but instead what you are doing is calling the function and then assigning the return value of that as a listener.
You need this instead, and I think it shouldn't crash anymore.
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
addEventsToMap(".event");
});
If that doesn't work, I would recommend looking at the Javascript Console of whatever browser you are using, to see what error is happening to make the map crash.