Create google maps polyline from multiple mysql points - mysql

I have a mysql table with a series of lat/lng points being written to an xml file and imported to google maps as points. This seems to be working fine, but rather than simply marking them with a point I'd like to generate a polyline between each of them. In looking at the developer docs, I noticed that the example iterates through creating a new latlng object for each line/ set of points. Is there a way I can dynamically call a series of points to generate multiple lines from my database? Sorry if this seems like an obvious fix- I'm a bit new to the maps api. Thanks in advance!
The output XML file I'm using looks something like this:
Location name="2012-04-01 12:28:18" lat="42.9523010667" lon="-78.8189444333"/
Location name="2012-04-01 12:28:06" lat="42.95219345" lon="-78.81931905"/
Location name="2012-04-01 12:27:54" lat="42.9522356" lon="-78.8192848667"/..... etc
HTML/ Script Calling the XML coords into the map:
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("timestamp");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lon")));
var marker = createMarker(point, name);
map.addOverlay(marker);
}
});
Code snippet in question on developers.google doc:
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2});
flightPath.setMap(map);}}}
function createMarker(point, name) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
I'm currently not showing any errors in the console. This is how I've attempted to implement the two previous code snippets from the original post, but I'm not getting the map to display any lines/ points. Might it be the way I'm defining the point variable/ it is not storing the array, but a single point?? I've tried using [] in defining "point" as well- but this didn't work/ didn't show any errors either...
function load() {
if (GBrowserIsCompatible()) {
// Create an instance of Google map
var map = new GMap2(document.getElementById("map"));
// Tell the map where to start
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
for (var i = 0; i < markers.length; i++) {
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon")));
var polyline = new GPolyline(point, '#ff0000', 5, 0.7);
map.addOverlay(polyline);
}
});
}}

Got it!
Here I was asking the internet, and the kid sitting behind me knew the whole time...
I was setting up the array incorrectly. To solve the problem:
----create an empty array
----use '.push' to insert into array
function load() {
if (GBrowserIsCompatible()) {
// Create an instance of Google map
var map = new GMap2(document.getElementById("map"));
// Tell the map where to start
map.setCenter(new GLatLng(42.9521, -78.8198), 20);
GDownloadUrl("gmaps_genxml2.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("Location");
var points = [];
for (var i = 0; i < markers.length; i++) {
points.push(new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon"))));
}
var polyline = new GPolyline(points, '#ff0000', 5, 0.7);
map.addOverlay(polyline);
});
}}

Related

Google maps Spiderfier, map unresponsive after setmap(null)

I have a function that loads my map to keep my map static.
<script>
var delArray = new Array();
var gm;
var map;
var iw;
var oms;
window.onload = function(){
gm = google.maps;
map = new gm.Map(document.getElementById('map_canvas'), {
mapTypeId: gm.MapTypeId.TERRAIN,
center: new gm.LatLng(-29.335205, 24.793563),
scrollwheel: false,
zoom: 6
});
iw = new gm.InfoWindow();
oms = new OverlappingMarkerSpiderfier(map,
{markersWontMove: true, markersWontHide: true});
}
</script>
I then use another function to construct my spiderfier data.
<script>
function spider(mapData){
var usualColor = 'eebb22';
var spiderfiedColor = 'ffee22';
var iconWithColor = function(color) {
return 'http://chart.googleapis.com/chart?chst=d_map_xpin_letter&chld=pin|+|' +
color + '|000000|ffff00';
}
var shadow = new gm.MarkerImage(
'https://www.google.com/intl/en_ALL/mapfiles/shadow50.png',
new gm.Size(37, 34), // size - for sprite clipping
new gm.Point(0, 0), // origin - ditto
new gm.Point(10, 34) // anchor - where to meet map location
);
oms.addListener('click', function(marker) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
iw.close();
});
oms.addListener('unspiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(usualColor));
markers[i].setShadow(shadow);
}
});
var bounds = new gm.LatLngBounds();
for (var i = 0; i < mapData.length; i ++) {
var datum = mapData[i];
var loc = new gm.LatLng(datum[0], datum[1]);
bounds.extend(loc);
var marker = new gm.Marker({
position: loc,
title: datum[2],
animation: google.maps.Animation.DROP,
map: map,
icon: iconWithColor(usualColor),
shadow: shadow
});
marker.desc = datum[3];
oms.addMarker(marker);
delArray.push(marker);
}
map.fitBounds(bounds);
// for debugging/exploratory use in console
window.map = map;
window.oms = oms;
}
</script>
And Another to remove markers from the map:
<script>
function delMe(){
if(delArray){
for(i =0; i <= delArray.length; i++){
delArray[i].setMap(null);
}
this.delArray = new Array();
}
}
</script>
My map data (mapData) comes from a php script and passed on via Jason. And that's also where I call my delete function right before I call my spider (map) function. This I do to clear the map before I pass the new data.
$( document ).ready(function() {
delMe();
var pdata = $js_array;
spider(pdata);
});
Now, my problem is that all data is displaying perfectly but after calling the delMe() function it clears the markers 100% but then my map become unresponsive it's not loading new data when calling the spider() function with new data.
I can overcome this problem by reloading/creating the map again, but I want to avoid that and only use a static map. And if I don't delete markers it just fill the map with 100's of markers mixing the old and new.
I am a bit of a noob when it comes to javascript/jquery, any help will be much appreciated!.
It looks like you're missing an OMS removeMarker call in your delMe function, which should go something like this:
function delMe(){
if (delArray){
for (i =0; i <= delArray.length; i++){
oms.removeMarker(delArray[i]);
delArray[i].setMap(null);
}
this.delArray = [];
}
}
(It's possible you have other problems too, but here's a start).
It's not clear from what you write, but are you using the JS developer console? Google '[your browser] developer console' for more info — it lets you see if errors are causing your map to become unresponsive.

Saving google map polygon as rails record

As rails 3.2.18 postGIS enabled application needs to capture polygon data from google maps API.
The js is as follows:
var poly, map;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var roma = new google.maps.LatLng(41.877, 12.480);
map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: roma,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
poly = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
poly.setMap(map);
poly.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addPoint);
}
function addPoint(event) {
path.insertAt(path.length, event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
marker.setTitle("#" + path.length);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
markers.splice(i, 1);
path.removeAt(i);
}
);
google.maps.event.addListener(marker, 'dragend', function() {
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
path.setAt(i, marker.getPosition());
}
);
}
While the map generates the polygon, I would like to, in a first instance view the LatLng points (to track what is being generated), but ultimately save the points.
A first issue is LatLng (Google) vs Lon/Lat (PostGIS). While there is always the possibility of flipping the data, I'd just assume avoid it. THis would imply some parsing of the data.
So how can the polygon points get captured to the database, individually or as a LonLat-formatted polygon? [Bear in mind I'm really not proficient in js...]
I'd probably want to make an AJAX request to a ruby script that would then save the details to the DB. You can access the individual latitude and longitude values from your event like so:
event.latLng.lat()
event.latLng.lng()
Or indeed use the lat() and lng() functions on anything that returns a LatLng object. See the docs: https://developers.google.com/maps/documentation/javascript/reference#LatLng

google maps api v3 center map after reading xml file

I'm in the process of updating my google maps code to version 3 and i've come across a problem.
In version 2, I was reading in an xml file to create a marker and I was centering my map based on the coordinates, but in version 3 the center has been defined in the map variable before the xml file has been read.
Is this easy to fix?
Version 3 code taken from http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("results.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("event");
var address = markers[i].getAttribute("location");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
Maybe you mean map.setCenter(latlng:LatLng) ?Parse your xml, create the markers,then center the map where you want.

Javascript - Google api refresh event

Im doing a php web, that refresh its content with ajax and map is refreshed calling with a timer the load() function of the map.. thats no problem
My problem is, i have to put a map.setCenter first time. Imagine i start to search a marker i put in the map, and then after 20 seconds it reloads the map and it is going again to my "setCenter".. i dont want that. I want to refresh but the map STAYS where i am searching...
is there any function for doing that? here is my load function
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(-34.603365,-58.379416),11);
map.enableScrollWheelZoom();
GDownloadUrl("creoXml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("numMovil");
var type = "Movil";
var nameTit = "Móvil "+name;
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitud")),
parseFloat(markers[i].getAttribute("longitud")));
var marker = createMarker(point, nameTit,type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, name,type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>" + name + "</b>";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
look that everytime i call load(), my setCenter is that.. and if i remove the setCenter with a condition, the map turns into white.. thanks
Put a global variable in you code and call it loading=1.Then in your load function put something like this
if(loading==1){
setCenter....
loading=0;
}

Google fusion tables data and changing image to markers

Here is my problem. I want to set different image to standard markers given by fusion tables. I extract data from the column that contains my points "(coord,coord)" BUT when I associate this coordinates to a marker, this one is not showed! I think that the solution is soooo easy but I can't get it :(. Please read in the section "HERE IS THE PROBLEM" in the middle of this code to have a clear idea. Thanks!!!!
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(46.06454, 13.23561), //the center lat and long
zoom: 9, //zoom
mapTypeId: google.maps.MapTypeId.ROADMAP //the map style
});
//make gviz request
setData();
}
/* GVIZ - get data from Fusion Tables */
function setData() {
//create a viz query to send to Fusion Tables
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT dove FROM 781907"));
//set the callback function that will be called when the query returns
query.send(getData);
}
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
for (i = 0; i < numRows; i++) {
var row = response.getDataTable().getValue(i,0);
codeAddress(row);
}
}
var geocoder;
function codeAddress(latlng) {
// HERE IS THE PROBLEM!!!!
// Test show correctly "(lat,lng)" BUT no marker showed on the map!
document.getElementById("test").innerHTML = latlng;
geocoder.geocode( { 'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: latlng
//icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}
});
}
UPDATE: Based on #Trott's answer, maybe something like this? But still not running. Any advice?
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
//create an array of row values
for (i = 0; i < numRows; i++) {
rowtext = response.getDataTable().getValue(i,0);
var strArr[] = rowtext.split(",");
document.getElementById("via").innerHTML = rowtext;
row = new google.maps.LatLng(strArr[0],strArr[1]);
codeAddress(row);
}
}
geocoder.geocode() requires a LatLng object. Your variable latlng is simply text. You'll need to find a way to convert it to a LatLng object. Most obvious way is probably to parse it with a regex or some other way and pass the lat and lng to new google.maps.LatLng(). There may be a more elegant solution, but that will work.
If it helps, here's some quick hacking I did to your code to confirm what I wrote above. I just hardcoded your first pair of coordinates. You'll still need to write something to parse the data.
function codeAddress(latlng) {
//Whoops, latlng is a string. We need it to be an object. Let's just hardcode one for demo purposes.
latlng=new google.maps.LatLng(46.0724339, 13.249490000000037);
geocoder.geocode( { 'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}
});
}
UPDATE: If you (#Massimo) want to do it the way you have it in your update, then you need to remove the parentheses and possibly white space. Try something more like this:
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
//create an array of row values
for (i = 0; i < numRows; i++) {
var rowtext = response.getDataTable().getValue(i,0);
var sanitizedText = rowtext.replace(/[\(\)\s]/g, "");
var strArr = sanitizedText.split(",");
document.getElementById("via").innerHTML = rowtext;
row = new google.maps.LatLng(strArr[0],strArr[1]);
codeAddress(row);
}
}