Setting multiple toggleable KML layers on GoogleMaps with custom icons - javascript

I would like to create a Google map with toggleable KML layers - every layer has its set of icons. Example of a map I would like to use can be seen here.
I am unable to set separate layers on the map so I can continue with making them toggleable one by one.
These are my steps for obtaining data for KML layers on Google map:
1. Select "Download KML"
2. I chose a layer ("Food stores" for example)
- I checked "Keep data up to date with network link KML" (Map will be maintained on Google maps and data should automatically refresh in my map on the website).
- I left unchecked "Export to a KML file" (because of the icons support)
Then I unzip downloaded files. Inside small code there is <href>http://www.google.com/maps/d/kml?mid=16i6f7Jvm754_jzkltP-Ks_2pKbU&lid=M97Oy53L0t4</href> which I include in url of sitesLayer when passing data for function loadKml() at the bottom of the following code.
The problem with this is that I instantly get all those icons on the map, even if I have downloaded and included only 1 layer - the map shows all 4 of them.
Am I missing something, in the code or in the steps for downloading KML files for separating layers/icons?
function initialize() {
// Map settings
var myLatlng = new google.maps.LatLng(0,0);
var mapOptions = {
zoom: 18,
center: myLatlng
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Creating KML layers
loadKml = function(opts,map){
var layer = new google.maps.KmlLayer();
opts.preserveViewport = true;
if(map) {
opts.map = map;
}
google.maps.event.addListener(layer,'defaultviewport_changed',function() {
var map=this.getMap(),
bounds=map.get('kmlBounds') || this.getDefaultViewport();
bounds.union(this.getDefaultViewport());
map.set('kmlBounds',bounds);
map.fitBounds(bounds);
});
layer.setOptions(opts);
return layer;
}
// Setting KML layers
var sitesLayer = loadKml({
url: 'http://www.google.com/maps/d/kml?mid=1AQ5Is7NjBGjPZpLji5fbApYnegk&lid=z-AEWAAfH9c',
map: map
});
var sitesLayer2 = loadKml({
url: 'http://www.google.com/maps/d/kml?mid=16i6f7Jvm754_jzkltP-Ks_2pKbU&lid=jY6tGqHtk80',
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);

Related

HTML/JS - Google Maps v3 - select/remove marker by id from external link

I'm new to google maps and javascript . I'm trying to interact with the map using external links/lists.
My main problem is that i'm unable to select the marker on the map with its id.
I don't want to put all markers in a list/array and iterate over them since i don't know how many there will be at any point.
I simply want to select them by their id and work with them such as opening infowindow , removing them etc...
in my changeIcon() function , i tried some ways but none worked so far .
<html>
....
<div id="mapview"></div>
<a class="test-link" onmouseover="changeIcon()">Link</a>
<script>
function changeIcon()
{
//marker = map.selectMarker("4");
//marker = markers[4];
//infowindow.open(map,marker);
//$("#mapview").map.removeMarker(4);
}
var map = new google.maps.Map(document.getElementById('mapview'),
{
center: {lat: 44.540, lng: -78.546},
zoom: 16
});
function initMap()
{
var marker = new google.maps.Marker({
position: userPosition,
map: map,
id: 4
});
}
</script>
</html>
............................................
There is no API to get marker from map. ref:
"https://developers.google.com/maps/documentation/javascript/reference"
I think you dont want to use array because id will never match the index. So I suggest using dictionary:
var markers = {}; // "{}" to specify dictionary instead of "[]" to specify array
when you create marker, you add it to dictionary:
markers[4] = marker; // 4 is the id
when you want to get it:
var currentMarker = markers[4];

Google maps js api. Many maps on page

I have accordion (twitter-bootstrap), and on each I have a map.
Accordion blocks generates in foreach. Maps generates as partial view, that takes model with latitude and longitude and block id.
It calls in foreach:
#if (item.Latitude != null)
{
<p>Map:</p>
<div class="map-margin">
#{Html.RenderAction("Map", "Default", new {model = item});}
</div>
}
And action returns this partial view:
#model MPS.Administration.Models.ReportModel
<div id="map-canvas-#Model.Id.ToString()" style="width: 470px; height: 270px;"></div>
<script type="text/javascript">
$('#map-canvas-#Model.Id').ready(function() {
initialize();
});
function initialize() {
var lat = #Model.Latitude;
var lng = #Model.Longitude;
var latlng = new google.maps.LatLng(#Model.Latitude, #Model.Longitude);
debugger;
var mapOptions = {
center: latlng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var name = 'map-canvas-' + #Model.Id.ToString();
var map = new google.maps.Map(document.getElementById(name),mapOptions);
debugger;
// create a marker
var image = '../Content/Images/map_icon.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
}
</script>
On layout I included script for js api.
Now I have 4 blocks, but only the last have map block (and it have only google logo and gray background without the map :( ). In debugger I see that lat and lng is same all 4 times. I think the problem is how I call initialize() map. Please help me to solve this issue.
The map si show only in the visible div. For the other you shuuld see only a grey background and in some case a small portion of the map in the upper left corner.
For see the map in every block you should use map.resize() or better use a genaration function for each time you show a new map. Initialize tipcally is call only when the windows is created and this this case the maps not visible fails

map as div background - Google Maps API

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!

Rendering multiple Google Maps API V3 markers from JSON

Attempting to plot multiple markers using Google Maps API V3 from JSON output by PHP from DB.
Map is initialized on page, however it does not populate with markers. Browser warns "Resource interpreted as Other but transferred with MIME type undefined."?
Suggestions for further troubleshooting / debugging please.
<!-- load points from database into Locations JSON -->
$(document).ready(function () {
$.getJSON("map-service.php?action=listpoints", function(json) {
if (json.Locations.length > 0) {
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
addMarker(location);
}
}
});
function addMarker(location) {
var point = new google.maps.LatLng(location.lat, location.lng);
var marker = new google.maps.Marker({
position:point,
map: map,
title: location.name
});
};
});
Validated sample JSON output from map-service.php?action=listpoints
{"Locations":[{"name":"Abco Mountain","lat":"49.424999","lng":"-125.855003"},{"name":"Adder Peak","lat":"49.248333","lng":"-125.320000"},{"name":"Alexandra Peak","lat":"49.738110","lng":"-125.489998"},{"name":"Argus Mountain","lat":"49.538612","lng":"-125.389999"},{"name":"Big Baldy Mountain","lat":"49.759998","lng":"-126.129997"}]}
My problem stemmed from how I had initialized the original map object. It wasn't visible in the code I shared ... apologies.
I did this:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
and should have done this:
this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
I found the solution in this post Adding markers after map created Thanks #yitwail !
Try using jquery $.each for your looping.
if (json && json.Locations) {
$.each(json.Locations, function() {
addMarker(this);
});
});
Also, you'll probably want to call parseFloat on the lat and longiture inside your addMarker function.

Retrieve position of a google maps v3 marker to Qt in a desktop app with QtWebKit

I'm building a Qt app with Python where you can point and click at a (google) map and get the coordinates of the location. The map is shown through a QWebView loading a simple HTML page and the user can create markers by clicking. Screenshot of the widget after clicking on the map.
However, I'm having trouble to retrieve the just-clicked location coordinates back to Qt (so that I can use them as variables -- and, for example, show them in the QLineEdits on the topleft corner above, as current location of the marker).
This is the relevant part of the HTML file:
<script type="text/javascript">
var map;
function initialize() {
var local = new google.maps.LatLng(-23.4,-40.3);
var myOptions = {
zoom: 5,
center: local,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'rightclick', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
function dummyTxt() {
return 'This works.';
}
</script>
I've been trying with evaluateJavaScript, but was not able to retrieve the coordinates. I tried to created a function to access the position with marker.getPosition(), but with no luck. The dummy below works though..
newplace = QWebView.page().mainFrame().evaluateJavaScript(QString('dummyTxt()'))
>>> print newplace.toString()
This works.
Any suggestions on how to get the coordinates back to Qt?
Edit:
Here is the code that worked for me:
def update_geo(self):
# Capture coordinates of the last marker on the map.
mark = self.map.page().mainFrame().evaluateJavaScript('document.getElementById("markerlocation").value').toString()
# Convert string to list of floats, stripping parentheses.
marker = str(mark).strip('()').split(', ')
decimals = [float(c) for c in marker]
Full source in https://github.com/nelas/veliger/blob/master/veliger.py#L2374
I found a work around to make it work but I'm not pretty sure that it will be the right approach. Anyway, this is what I did:
Create a hidden input in the body section of your html document to save the position data of the marker:
<body>
(...)
<input id="locationData" type="hidden">
(...)
</body>
In the javascript code, save the position of the marker in the hidden input every time it's created:
function placeMarker(location) {
(...)
document.getElementById("locationData").value = marker.position;
(...)
}
In your Qt code, read the value of the hidden input with the instruction:
webView->page()->mainFrame()->findFirstElement("#locationData").evaluateJavaScript("this.value").toString();
I hope it helps!
Source: http://opendocs.net/qt/4.6/webkit-formextractor.html

Categories

Resources