Rendering multiple Google Maps API V3 markers from JSON - javascript

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.

Related

Setting multiple toggleable KML layers on GoogleMaps with custom icons

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);

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];

How to iterate data to create markers for Google Maps (using express/jquery/ajax) currently getting SyntaxError

I initialize a google map here: (which is working fine, but I'll include for background)
this entire code comes inside of a .ejs file
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
var loadMap = function() {
var myOptions = {
center: new google.maps.LatLng(39.952335, -75.163789),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
};
</script>
</head>
<body onload="loadMap()">
then when I try to iterate over my date to add my markers - I get an error (code works without this segment in it)
This is what I have so far:
Also note that because of express (I think it's express at least) I can use the <% code code code %> to write javascript inside of an html file.
<!-- data is an array of arrays [name, lat, lon, description, creator] -->
<% for (var i = 0; i < array[0].length; i++) {
var info = new google.maps.InfoWindow();
info.setContent( %><b><% "Name: "+array[0][i] %></b><% +". Description: "+array[3][i] %><i><% +". Creator: "+array[4][i] %></i><% );
var newCoords = new google.maps.LatLng(array[1][i], array[2][i]);
var marker = new google.maps.Marker({
position: newCoords,
map: map,
title: array[0][i],
if (message == array[0][i]) { // if the creator is currently signed in (his additions should be yellow on map)
icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
}
});
google.maps.event.addListener(marker, 'click', (function(info, marker) {
return function() {
info.open(map, marker);};
})(info, marker))
}; %>
I'm getting a Unexpected Token : ';'
In case there's any confusion there I'm trying to add new markers for the data in my array, have it be clickable and display text in there that's partly bolded, partly italicized.
also, im using closure at the end there to make sure each event listener is unique (copied from here: Javascript: Looping through an array to create listeners, issue with call by reference and value?)
Hope eyes more experienced than I can spot my error or suggest a better alternative... I've tried taking out every single non-essential semi-colon but it accomplished nothing..
Syntax error, marker should be:
var marker = new google.maps.Marker({
position: newCoords,
map: map,
title: array[0][i],
icon : (message == array[0][i])? //use ternary
'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
: undefined
});
You can't have if statements in an object literal but you can assign icon with a ternary expression. If it's a problem that icon is undefined you can do it outside the object literal:
var info = new google.maps.InfoWindow(),
markerDetails;
//...code
markerDetails = {
position: newCoords,
map: map,
title: array[0][i]
};
if (message == array[0][i]) {
markerDetails.icon = 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
}
var marker = new google.maps.Marker(markerDetails);

Google maps spiderfy function - more than one marker at the same point

I'm trying to use the Overlapping Marker Spiderfier for Google Maps API v3 found here. (my questions are at the bottom of this block of text/code)
https://github.com/jawj/OverlappingMarkerSpiderfier/blob/master/README.textile
The page I'm trying to implement it on is a bit different than the code they use on their source code page. They initialize their page and implement all of their function calls within the initialization function. My page initializes the map and loads one point, and then additional points are added later using a separate function (through geocoding).
So, essentially at this point the map has been initialized, now I call my database to get new locations to add.
var cityArray= <?php echo json_encode($cityArray); ?>; //get the city
var title = <?php echo json_encode($title); ?>; //and the title to go on it's infowindow
function plotMarkers(){
for(var i = 0; i < <?php echo json_encode($length); ?>; i++){
codeAddresses(cityArray[i],title[i]); //geocode the address
}
}
So, this snippet above gives me two arrays; one with a location, and one with the title to go in the info window. The
So, now here's the codeAddresses function that geocodes the address, and adds that marker to the map. As you can see from the plotMarkers function, the arrays are looped through and added to the codeAddresses funciton.
function codeAddresses(address,title){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker) {
return function() {
infowindow.setContent(title);
infowindow.open(map, marker);
}
})(marker));
}
});
}
My question is do I add the listeners (on the page linked above) to my first function that loads the first point, or should I add it to the codeAddresses function?
Also, should I include this in my codeAddresses function or somewhere else? If it does go in codeAddresses, does that mean I can get rid of the for loop because codeAddresses is triggered from a loop (and gets run during each iteration)?
for (var i = 0; i < window.mapData.length; i ++) {
var datum = window.mapData[i];
var loc = new gm.LatLng(datum.lat, datum.lon);
var marker = new gm.Marker({
position: loc,
title: datum.h,
map: map
});
marker.desc = datum.d;
oms.addMarker(marker); // <-- here
}
The best strategy is to geocode the addresses offline (using the geocoding web service), store the coordinates in your database, then use them to display the markers, this will reduce the time to load your page since the geocoder is subject to rate limits and quotas.

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