geoxml3 adding events on placemarks - geoxml3

I am trying to add events on placemarks but getting an error 'docs is undefined'. When I try and alert the names of the placemarks, they work fine so why not the events?
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var geoXml = new geoXML3.parser({
map: this.map,
singleInfoWindow:true,
afterParse: this.useTheData
});
geoXml.parseKmlString(<my kml string>);
google.maps.event.addListener(this.map, "bounds_changed", RefreshMap);
google.maps.event.addListener(this.map, "center_changed", RefreshMap);
google.maps.event.addListener(this.map, "zoom_changed", RefreshMap);
},
useTheData: function(doc) {
for (var i = 0; i < doc[0].placemarks.length; i++) {
docs[0].placemarks[i].events.add("click", function () {alert("event!!");});
//alert(docs[0].placemarks[i].name);
}
}

"docs" is undefined. The local version is "doc".
the .placemark is a JSON representation of the Placemark, not a google maps object that will handle click events.
It contains a reference to the google maps object (.placemark.marker for a marker) that you can add a click event listener to.
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var geoXml = new geoXML3.parser({
map: this.map,
singleInfoWindow:true,
afterParse: this.useTheData
});
geoXml.parseKmlString(<my kml string>);
google.maps.event.addListener(this.map, "bounds_changed", RefreshMap);
google.maps.event.addListener(this.map, "center_changed", RefreshMap);
google.maps.event.addListener(this.map, "zoom_changed", RefreshMap);
},
useTheData: function(doc) {
for (var i = 0; i < doc[0].placemarks.length; i++) {
google.maps.event.addListener(
doc[0].placemarks[i].marker,
"click",
function () {alert("event!!");
});
//alert(docs[0].placemarks[i].name);
}
}

Related

Mapbox GL Directions - mapboxgl.Directions is not a constructor

I have an issue with mapbox direction plugin, on a rails app. When I load the page where the map is, I have this error :
Uncaught TypeError: mapboxgl.Directions is not a constructor
at HTMLDocument.<anonymous> (travel.self-10030a4….js?body=1:34)
at fire (jquery.self-bd7ddd3….js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd3….js?body=1:3363)
at Function.ready (jquery.self-bd7ddd3….js?body=1:3583)
at HTMLDocument.completed (jquery.self-bd7ddd3….js?body=1:3618)
Here is the code for my map :
var map;
var directions;
// token access for MAPBOX GL
mapboxgl.accessToken = 'pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw';
// generate map
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [-96, 37.8],
zoom: 5
});
// center map on selected marker
map.on('click', 'markers', function (e) {
map.flyTo({center: e.features[0].geometry.coordinates});
});
// change mouse action on enter / leave in marker
map.on('mouseenter', 'markers', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'markers', function () {
map.getCanvas().style.cursor = '';
});
// Directions
var directions = new mapboxgl.Directions({
unit: 'metric',
profile: 'driving',
container: 'directions'
});
$.ajax({
dataType: 'json',
url: grabTravelData(),
success: function(data) {
geojson = data;
map.addSource("markers", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": data
}
});
map.addLayer({
"id": "markers",
"type": "circle",
"source": "markers",
"paint": {
"circle-radius": 7,
"circle-color": "#ff7e5f"
},
});
// center map on markers
var bounds = new mapboxgl.LngLatBounds();
data.forEach(function(feature) {
bounds.extend(feature.geometry.coordinates);
});
map.fitBounds(bounds);
// test - set direction for each marker to following marker
for(var i = 0; i < data.lenght; i++) {
var last = data.length - 1
var from = data[i];
var to = data[i + 1];
directions.setOrigin(from);
if(to != from) {
directions.setDestination(to);
} else {
directions.setDestination(from);
}
}
}, error: function(data) {
console.log(data + ' error');
}
});
In this code, with a for loop I try to create a routes between each markers with the following marker.
In the header of the app I import mapbox :
<script src='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet' />
<script src="https://cdn.jsdelivr.net/places.js/1/places.min.js"></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.css' type='text/css' />
Doest someone know what is this error ?
The proper way to use the Mapbox GL directions is
var directions = new MapboxDirections({
accessToken: 'YOUR-MAPBOX-ACCESS-TOKEN',
unit: 'metric',
profile: 'cycling'
});
map.addControl(directions);
For more details refer the API Documentation

how to create costume marker icon rails google maps

i am developing google maps project so i want create costume marker icon here my code in javascript
`window.onload = function initmap() {
var markers = <%=raw #json.to_json %>;
var icon = {
url: '/home/amarnath/Project/myCarparking/app/assets/images/001-map.svg',
size: new google.maps.Size(15, 20),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15/2, 20/2)
};
var infoWindow = new google.maps.InfoWindow({map: map});
var map = new google.maps.Map(document.getElementById("map_places"));
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
center: geolocpoint,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_places"), mapOptions);
var geomark = new google.maps.Marker({
position: geolocpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Your geolocation',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.marker_title,
icon: '/home/amarnath/Project/myCarparking/app/assets/images/parking_full.png'
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.infowindow);
infoWindow.open(map, marker);
});
})(marker, data);
}
});
}
}`
and i getting error like this
parking_full.png:1 GET http://localhost:3000/home/amarnath/Project/myCarparking/app/assets/images/parking_full.png 404 (Not Found)
Move your icon to /assets/images folder and add following code:
icon: "/assets/parking_full.png"

trigger a marker click

I am using a Fusion Table and the Google Map API and would like to know if I can automatically trigger an event when a marker is placed.
Currently I can click on the map and I get a customized infowindow, but I want to do the same thing but after geocoding and placing a marker... I would like this to happen automatically.
Here is my code so far:
var FusionTableID = '<?php echo get_theme_mod( 'fusion_id' )?>';
var map = null;
var geocoder = null;
var marker = null;
function initialize() {
geocoder = new google.maps.Geocoder();
var local = new google.maps.LatLng(<?php echo get_theme_mod( 'lat-long' )?>);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: local,
zoom: <?php echo get_theme_mod( 'zoom' )?>
});
// forces a refresh to from Fusion Tables
//var and=' geometry does not contain "'+new Date().getTime()+'"';
var layer = new google.maps.FusionTablesLayer({
//suppressInfoWindows: true,
query: {
select: "col2\x3e\x3e0",
from: FusionTableID,
where: ""
},
options: {
styleId: 2,
templateId: 2
},
map: map
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(e) {
var point = e.latLng.toUrlValue(6);
var latlngStr = point.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position: latlng,
map: map
});
console.log(e.row['objectid'].value);
var tname = e.row['name'].value; // name
var targetDist = e.row['description'].value; // description
// poplulate the infowindow
e.infoWindowHtml = "<div class=\"grid-100\"><h2>"+tname+"</h2>"+targetDist+"<hr></div>";
});
}
function showAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
// THIS DOESN'T WORK ****
new google.maps.event.trigger( marker, 'click' );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Thanks geocodezip
It isn't really possible to "trigger" a click on a FusionTablesLayer (you can, but you basically need to replicate the information in the click event, which is painful), you can query the table an create your own infowindow on the marker though

Show markers on google maps dynamically -Rails 3.2

i have a working code that shows multiple markers on google map using geocoder such as
#nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km)
#nearbys.first(5)
and i display the markers using the below code
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
map.setTilt(45);
// adding Multiple Markers from ruby object
var markers = [
['<%= #nearbys[0].title %>', '<%= #nearbys[0].latitude %>','<%= #nearbys[0].longitude %>'],
['<%= #nearbys[1].title %>', '<%= #nearbys[1].latitude %>','<%= #nearbys[1].longitude %>'],
['<%= #nearbys[2].title %>', '<%= #nearbys[2].latitude %>','<%= #nearbys[2].longitude %>'],
['<%= #nearbys[3].title %>', '<%= #nearbys[3].latitude %>','<%= #nearbys[3].longitude %>']
,
['<%= #nearbys[4].title %>', '<%= #nearbys[4].latitude %>','<%= #nearbys[4].longitude %>']
];
// adding Info Window Content
var infoWindowContent = [
['<div class="info_content" >' +
'<h3><%= #nearbys[0].title %></h3>' +'</br>'+
'<p><%= #nearbys[0].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[1].title %></h3>' +
'<p><%= #nearbys[1].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[2].title %></h3>' +'</br>'+
'<p><%= #nearbys[2].about %></p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[3].title %></h3>' +'</br>'+
'<p><%= #nearbys[2].about %>/p>' +
'</div>'],
['<div class="info_content">' +
'<h3><%= #nearbys[4].title %></h3>' +'</br>'+
'<p><%= #nearbys[4].about %></p>' +
'</div>']
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends
BUT the problem is:-what if #nearbys has less than 5 count,then this code fails.SO i have been trying to make it dynamic using jquery arrays but its not working because i think my code is missing something to work it dynamically.
it should be something like this..
var array=<%= #nearbys%>;
var markers=[];
var infowindows=[];
array.each(function(index){
markers.push('<%= #nearbys[0].title %>', '<%= #nearbys[0].latitude %>','<%= #nearbys[0].longitude %>');
infowindows.push('<div class="info_content" >'+'<h3><%= #nearbys[0].title %></h3>' +'</br>'+
'<p><%= #nearbys[0].about %></p>'+'</div>');
})
..SO how i can achieve this........to make this dynamic so that above working code doesnt breaks with the newly added code.
well after struggling with jquery arrays and json ,i was able to find this best solution...this is working in all scenarios and all i need is to handle empty and null conditions,which i already did and its working the way i needed.HOPE THIS HELPS SOMEONE
my controller
def show_nearby_locations
#nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km)
#nearbys.first(10)
end
in my view file
<%= javascript_tag do%>
window.nearbys= <%=raw #nearbys.to_json %>;
<%end%>
this is my script inside view
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas-guest"), mapOptions);
map.setTilt(45);
var markers=[];
var infoWindowContent=[];
$.each(nearbys, function(index) {
console.log( data[0][index].latitude,data[0][index].longitude );
markers.push([nearbys[index]['title'], nearbys[index]['latitude'],nearbys[index]['longitude']]);
infoWindowContent.push(['<div class="info_content" >' +
'<h3 style="color: rgb(<%= rand(0..200)%>,<%= rand(0..200)%> ,<%= rand(0..200)%>);">'+nearbys[index]['title']+'</h3>' +'</br>'+
'<p>'+nearbys[index]['about']+'</p>' +
'</div>']);
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends
Hello Friends by doing with Google Maps With Rails i have searched the information from google maps site and Gmaps4rails i have done Multiple Markers and Info-window her is the code
My Controller
#users = User.all
#hash = Gmaps4rails.build_markers(#users) do |user, marker|
marker.lat user.latitude
marker.lng user.longitude
marker.infowindow user.title`
end
In My View
window.onload = function () {
var markers = <%=raw #hash.to_json %>;
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}

GeoXML3 - Open an info window automatically

I have created a polygon and would like the info window to open automatically on load. How do I do this?
This is what I have so far:
var geoxml = null;
function initialize() {
infoWindow = new google.maps.InfoWindow();
var myLatlng = new google.maps.LatLng(100.9530044, 110.8574693);
var myOptions = {
maxZoom: 13,
center: myLatlng,
streetViewControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true,
infoWindowOptions: {maxWidth:350,cornerRadius: 12},
});
geoXml.parse('file.xml');
};
You can trigger a click on the placemark (polygon), when the KML is done rendering (the map idle event fires). This will open the infowindow on the first placemark:
google.maps.event.addListenerOnce(map, 'idle', function() {
google.maps.event.trigger(geoXml.docs[0].placemarks[0].polygon,'click')
});
working example

Resources