Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am trying to show some markers from a database in openlayers. I tried it in google maps in past using GDownloadURL fuction to read a json php generated file from my database.

Now I tried the same with openlayers and I am not able to do that. I read about incompatibility between php and javascript but I think there have to be a way to do what I want.

My file jsonZona.php returns an array like this: {"markers":[{"lng":"-3.880102031707764","lat":"43.46711564169348","limpio":"1"}, {"lng":"-3.862788677215576","lat":"43.4669443349282","limpio":"1"}]}

limpio is an option to select one icon or other one. It can be 0 or 1.

My code is:

<!DOCTYPE HTML>
<html>
<head>
<title>OpenLayers Demo</title>
<style type="text/css">
 body, #basicMap {
      width: 828px;
      height: 698px;
      margin: 10px;
      float: left;
 }
 html {
      font-size: 10px;
      bottom: 10px;
      right: 10px;
 }

</style>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>

<script>

var map;
var markers;


function ejecutar(){
    init();
    //loadMarkers();
}
function init() 
  {    
  map = new OpenLayers.Map ("basicMap", {
        controls:[
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.LayerSwitcher(),
            new OpenLayers.Control.Attribution()],
        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
        maxResolution: 156543.0399,
        numZoomLevels: 19,
        units: 'm',
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326")
      });

    // Define the map layer
    // Here we use a predefined layer that will be kept up to date with URL changes
    layerMapnik = new OpenLayers.Layer.OSM.Mapnik("MapaCiudad");
    map.addLayer(layerMapnik);
   var lonLat = new OpenLayers.LonLat(-3.8343143463134766,43.451610413300685).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
  //map.setCenter(new OpenLayers.LonLat(-3.862788677215576, 43.4669443349282) // Center of the map
    map.zoomTo(13);
    map.setCenter(lonLat, 19);  
    //loadMarkers();

    //Añadimos aqui la capa de los marcadores
    markers = new OpenLayers.Layer.Markers("Marcadores");               
    map.addLayer(markers); 
}



function loadMarkers(){
         //vectorLayer = new OpenLayers.Layer.Vector("Overlay");
         markers.clearMarkers();

         var selectBox = document.getElementById('zona');               
         if (selectBox.value == "0") return;

         jsonData = GDownloadUrl("jsonZona.php?zona=".selectBox.value); //pass zone to use in select on database

         var jsonData = eval('(' + doc + ')');
         alert(jsonData.markers[i].lat);
         var size = new OpenLayers.Size(21,25);
         var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);

         for (var i=0; i<jsonData.markers.length; i++) {
              var location = new OpenLayers.LonLat(jsonData.markers[i].lat, jsonData.markers[i].lng).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());

              if(jsonData.markers[i].limpio == 0)
               var icon = new OpenLayers.Icon('redMarker.png',size,offset);   
              if(jsonData.markers[i].limpio == 1)
               var icon = new OpenLayers.Icon('greenMarker.png',size,offset);   

             markers.addMarker(new OpenLayers.Marker(location,icon.clone()));


    }
  }


 </script>
</head>
<body onload="ejecutar();">
<div id="basicMap" ></div>
<label>Zona: </label>
<select id="zona" onchange="loadMarkers();">
    <option value="0">=== Selecciona una zona ===</option>
    <option value="1">Zona 1</option>
    <option value="2">Zona 2</option>  
    <option value="3">Zona 3</option>
    <option value="4">Zona 4</option> 
 </select>
</body>

Do you have any idea about how I can do that?

Also, I want to refresh markers each X minutes. I think I can use setTimeOut function to do it but I don't know how I can apply it here.

I edit: I think I can't use GDownloadURL function because it is related to google maps. How can I execute php code in javascript to take data?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

You make mistake in loadMarkers function:

 if(jsonData.markers[i].limpio == 0)
     var icon = new OpenLayers.Icon('redMarker.png',size,offset);   
 if(jsonData.markers[i].limpio == 1)
     var icon = new OpenLayers.Icon('greenMarker.png',size,offset);

After that icon variable is undefined. You should explode this variable before if statement

var icon;
if(jsonData.markers[i].limpio == 0)
     icon = new OpenLayers.Icon('redMarker.png',size,offset);   
else
     icon = new OpenLayers.Icon('greenMarker.png',size,offset);   

Probably this is why you can't display your markers. For refreshing markers better is setInterval function than setTimeout. This is sample: setInterval

edit:

In jQuery library you can call:

$.ajax({
  url: "jsonZona.php?zona=".selectBox.value
}).done(function() { 
  // Function to create markers, same as before
});
share|improve this answer
    
Hi, thanks. I corrected that. But it doesn't continue from jsonData = GDownloadURL... –  Biribu Apr 6 '12 at 9:46
    
GDownloadURL is a part of Google Maps API. You have to add this API to your page or use for example jQuery ajax function. –  Raknel Apr 6 '12 at 11:16
    
Thanks, that was my problem. –  Biribu Apr 6 '12 at 16:46
add comment

I've tried to move this over to http://jsfiddle.net/XjLcc/ so that it's easier to see the working code. When I cut/paste the raw HTML into the jsFiddle, it basically worked (well the map showed up properly). However, when splicing it into it's various separate parts it seemed to stop working. I'd love to have this example working properly in jsFiddle.

share|improve this answer
    
Finally I didn't use GDownload function. I found other problems I didn't know how to solve. I use othe function to read json file: $.getJSON("jsonFile.php?zona="+zona,function(jsonData){ Function to create markers, same as before}); –  Biribu Apr 15 '12 at 10:38
    
Biribu I add answer on question in my post up –  Raknel Apr 16 '12 at 10:44
    
you can't execute PHP in javascript. You can pass information to the server from Javascript and then process the result using AJAX, but Javascript is client side and PHP is server side. –  Mike Gifford Apr 17 '12 at 2:07
    
But, the way I use $.getJSON function works. I just tried in my local network. Would it work across the internet? –  Biribu Apr 22 '12 at 18:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.