ThinkGeo.com    |     Documentation    |     Premium Support

Adding popup for each point (JavaScript Mapping)

The code below is animating the vehicle actions on the map. But I tryed to add popup for each point when animation is showing each point (points are showed as arrow gifs). There is no problem when adding popups for each point but problem is that it opens popup window directly, however I want to open popup window when the mouse is over object.


How can I do that ?


 


////////////////////////////////////////////////////////////////////////////////////////// ON PAGE LOAD //////////////////////////////////////////////////////////////////////////////


 if (staticDt.Rows.Count > 0)

         {

                 

                  currentFleet = Convert.ToInt32(staticDt.Rows[0]["FLEETID"]);

                  

                  double firstX = 0;

                  double firstY = 0;

                  double xCoord = 0;

                  double yCoord = 0;


                  StringBuilder script = new StringBuilder();

                  script.Append("var Objects={aractip:")

                      .Append(staticDt.Rows[0]["ARACTIPID"].ToString())

                      .Append(",coords:new Array(");

                  StringBuilder jsString = new StringBuilder();

                  List<string></string> jsArray = new List<string></string>();


                  for (int i = 0; i < staticDt.Rows.Count; i++)

                  {


                    jsString.Length = 0;

                    xCoord = 0;

                    yCoord = 0;

                    double.TryParse(staticDt.Rows["X"].ToString(), out xCoord);

                    double.TryParse(staticDt.Rows["Y"].ToString(), out yCoord);

                    ConvertCoords(ref xCoord, ref yCoord);

                    if (i == 0)

                    {

                      firstX = xCoord;

                      firstY = yCoord;


                    }

                    int kontak = 0;

                    int.TryParse(staticDt.Rows["CONTAC"].ToString(), out kontak);

                    int aractip = 0;

                    double aci = 0;

                    double.TryParse(staticDt.Rows["DIRECTION"].ToString(), out aci);

                    int.TryParse(staticDt.Rows["ARACTIPID"].ToString(), out aractip);

                    bool rolanti = (bool)staticDt.Rows["ROLANTI"];

                    bool status = Convert.ToInt32(staticDt.Rows["STATUS"]) != 0;

                    DateTime InsertDate = Convert.ToDateTime(staticDt.Rows["INSERTDATE"].ToString());

                    int iStatus = 0;


                    TimeSpan tm = DateTime.Now - InsertDate;


                    if ((!status) && (tm.TotalMinutes >= 60))

                    {

                        iStatus = 4;

                    }

                    else

                    {

                        if (kontak == 1 && !rolanti) iStatus = 1;

                        else if (kontak == 1 && rolanti) iStatus = 2;

                        else if (kontak == 0) iStatus = 3;

                    }


                    jsString.Append("{")

                        .Append("'x':")

                        .Append(jsDouble(xCoord))

                        .Append(",")

                        .Append("'y':")

                        .Append(jsDouble(yCoord))

                        .Append(",")

                        .Append("'iDegree':")

                        .Append(Math.Round(aci).ToString())

                        .Append(",")

                        .Append("'iStatus':")

                        .Append(iStatus.ToString())

                        .Append("}");

                    jsArray.Add(jsString.ToString());

                  }


                  script.Append(String.Join(",", jsArray.ToArray()));

                  script.Append(")};");




                  Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rastgele", script.ToString(), true);

                  PointShape point = new PointShape(firstX, firstY);

                  Map1.ZoomTo(point, Map1.ClientZoomLevelScales[7]);

                }


/////////////////////////////////////////////////////////////////////////////////////// END PAGE LOAD ///////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////// SCRIPT ///////////////////////////////////////////////////////////////////////////////////////////////////////


 


 


function OnMapCreating(map) {


OpenLayers.Layer.Google = OpenLayers.Class(OpenLayers.Layer.Google, {


MIN_ZOOM_LEVEL: 5,


MAX_ZOOM_LEVEL: 17


});


}


function initPage() {


if (Objects)


{


recalcStatic();


parserMap1.map.events.register('movestart', parserMap1.map, function(evt) { mapWait(); });


parserMap1.map.events.register('moveend', parserMap1.map, function(evt) { mapDrawEnd(); });


}


else


{


document.getElementById('startinput').disabled = true;


document.getElementById('stopinput').disabled = true; 


alert("Konum bilgisi yok. Ltfen tarih kriterlerini kontrol ediniz.");


}


}


var waitForMap = false;


function mapWait() {


if (isAnimBegin) {


if (animHandler != null) {


window.clearTimeout(animHandler);


animHandler = null;


waitForMap = true;


//buttonCase(false);


}


}


}


function mapDrawEnd() {


if (isAnimBegin) {


beginAnimHandler();


//buttonCase(true);


}


}





function recalcStatic() {


userSinir=(Objects.coords.length < 10) ? 10 : Objects.coords.length


}


var startFrom = 0;


var animHandler = null;


var lastMarker = null;


var markersObj = null;


var tempVehicleMarker = null;


function putMarker(aractip,iStatus,x,y,stat,aci,durum) {


var marker;


//var markers = parserMap1.map.getLayersByName('vehicleLayer')[0];


var degAci = aci || 0;


var degDurum = durum || 1;


var size = new OpenLayers.Size(20, 20);


var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);


var imagePath =(!stat)?'images/vTypes/{0}/{1}.gif'.format(aractip, iStatus.toString().padLeft(3)): 'rotate.aspx?aci=' + aci + '&durum=' + durum;


var icon = new OpenLayers.Icon(imagePath);


var LonLat = new OpenLayers.LonLat(x, y);


marker = new OpenLayers.Marker(LonLat, icon);


parserMap1.map.panTo(LonLat);


markerLayer.addMarker(marker);


markersObj.push(marker);




//Add vehicle marker


if (tempVehicleMarker!=null)


{


markerLayer.removeMarker(tempVehicleMarker);


}


var imagePath ='images/vTypes/{0}/{1}.gif'.format(aractip, iStatus.toString().padLeft(3));


var icon = new OpenLayers.Icon(imagePath);


marker = new OpenLayers.Marker(LonLat, icon);




parserMap1.map.panTo(LonLat);


markerLayer.addMarker(marker);


tempVehicleMarker = marker;


}




function showNextMarker() {


if (startFrom + 1 > Objects.coords.length) {


stopAnim();


return;


}


var aci;


var durum;


if (markersObj == null) markersObj = new Array();


else {


var mrk = markersObj[startFrom - 1];


if (mrk.icon != null) {


var img = mrk.icon.imageDiv.getElementsByTagName('IMG');


//img[0].src = 'rotate.aspx?aci=' + Objects.coords[startFrom - 1]['iDegree'].toString() + '&durum=' + Objects.coords[startFrom - 1]['iStatus'].toString();


//isrc = 'rotate.aspx?aci=' + Objects.coords[startFrom - 1]['iDegree'].toString() + '&durum=' + Objects.coords[startFrom - 1]['iStatus'].toString();


aci = Objects.coords[startFrom - 1]['iDegree'].toString();


durum = Objects.coords[startFrom - 1]['iStatus'].toString();


}


}


document.getElementById('siraYaz').innerHTML = startFrom + 1;


var iStatus = Objects.coords[startFrom]['iStatus'].toString().padLeft(3);


var x = Objects.coords[startFrom]['x'];


var y = Objects.coords[startFrom]['y'];


 


------------------------------- I am trying to add popup here. the code below is working but open popup window directly, however I want to open popup window when the mouse is over object.

// var popup = new OpenLayers.Popup("example",


// new OpenLayers.LonLat(x,y),


// new OpenLayers.Size(200,200),


// "example popup",


// false);


 


// var map = Map1.GetOpenLayersMap();




// map.addPopup(popup);


-------------------------------------------------------------------------------------------------------------------------------------------


 


putMarker(Objects.aractip,iStatus,x,y,true, aci, durum);


startFrom++;


beginAnimHandler();


}




function beginAnimHandler() {


var Interval = 500;


if (!isNaN(document.getElementById('numerator').value)) {


Interval = document.getElementById('numerator').value * 100;


}


else {


document.getElementById('numerator').value = 5;


}


animHandler = window.setTimeout(showNextMarker, Interval);


}




function stopAnim() {


if (animHandler != null)


window.clearTimeout(animHandler);


startFrom = 0;


animHandler = lastMarker = markersObj = null;


isAnimBegin = false;


buttonCase(false);


}


function buttonCase(state) {


document.getElementById('startinput').disabled = state;


document.getElementById('stopinput').disabled = !state;


}


function startAnim() {


if (animHandler != null) {


stopAnim();


}


if (markerLayer == null) {


markerLayer = new OpenLayers.Layer.Markers('vehicleLayer');


parserMap1.map.addLayer(markerLayer);


}


buttonCase(true);


isAnimBegin = true;


markerLayer.clearMarkers();


showNextMarker();


}

 



 


 



Ayhan,



Popup and Marker are different objects, they do not have any relationship. You want to make your own markers and their hover popups, you need to build the relationship by your logic.



First of all, popup is visible by default when it is added on the map so that the popup is visible directly in your application. If you call "popup.hide();" after adding the popup on the map, it will be invisible by default.
var popup = new OpenLayers.Popup("example",
new OpenLayers.LonLat(x,y),
new OpenLayers.Size(200,200),
"example popup",
false);
 
var map = Map1.GetOpenLayersMap();
map.addPopup(popup);
popup.hide();

Secondly, you need to build a relationship between marker and popup.

For example marker.id = "marker1", the related popup.id = "popup_marker1". In this case, you can find the popup back from the map.popups property.

Now, the only thing left is to raise the hover event on the marker, please see the following code:marker1.events.register(‘mouseover’, marker1, function(e){
// find back the related popup.
// call popup.show() to show popup.
});

By the way, you can set an interval for showing and hiding popups, I think now you can handle the rest of the logic.



If you have any questions please let me know.



Thanks,

Howard



I tried several ways for doing this but I could not do it. sory... The code below works and give me different lonlat data for each popup but it does not hide the popup when I move the mouse on other object.


        var tmp_X = 0;

        var tmp_Y = 0;    

        function putMarker(aractip,iStatus,x,y,stat,aci,durum) {

            var marker;

            //var markers = parserMap1.map.getLayersByName('vehicleLayer')[0];

            var degAci = aci || 0;

            var degDurum = durum || 1;

            var size = new OpenLayers.Size(20, 20);

            var offset = new OpenLayers.Pixel(-(size.w / 2), -size.h);

            var imagePath =(!stat)?'images/vTypes/{0}/{1}.gif'.format(aractip, iStatus.toString().padLeft(3)): 'rotate.aspx?aci=' + aci + '&durum=' + durum;

            var icon = new OpenLayers.Icon(imagePath);

            var LonLat = new OpenLayers.LonLat(x, y);

            marker = new OpenLayers.Marker(LonLat, icon);

            parserMap1.map.panTo(LonLat);

            markerLayer.addMarker(marker);

            markersObj.push(marker);

           

   

            var popup = new OpenLayers.Popup("Example",

            new OpenLayers.LonLat(x,y),

            new OpenLayers.Size(100,100),

            LonLat,

            false);

            

            var map = Map1.GetOpenLayersMap();

             

            //marker.id = LonLat;

            //popup.id = LonLat;

             

            map.addPopup(popup);

            popup.hide();

            

            marker.events.register("mouseover", marker, function(e)

                                                                 {                                                                                                                                            

                                                                     if(tmp_X == 0)

                                                                     {

                                                                        tmp_X = e.x;

                                                                        tmp_Y = e.y;

                                                                        LonLat = new OpenLayers.LonLat(e.x, e.y)

                                                                        popup.show(LonLat);                                                                                                                                                                                                                   

                                                                     }

                                                                     if(tmp_X != e.x)

                                                                     {                                                                        

                                                                        LonLat = new OpenLayers.LonLat(tmp_X,tmp_Y)

                                                                        popup.hide(LonLat);                                                                        

                                                                        tmp_X = e.x;

                                                                        tmp_Y = e.y;                               

                                                                        LonLat = new OpenLayers.LonLat(e.x,e.y)                                        

                                                                        popup.show(LonLat);

                                                                     }                                                                                                                                              

                                                                    });            

             //Add vehicle marker

            if (tempVehicleMarker!=null)

            {

              markerLayer.removeMarker(tempVehicleMarker);

            }

            var imagePath ='images/vTypes/{0}/{1}.gif'.format(aractip, iStatus.toString().padLeft(3));

            var icon = new OpenLayers.Icon(imagePath);

            marker = new OpenLayers.Marker(LonLat, icon);                       

             

            parserMap1.map.panTo(LonLat);

            markerLayer.addMarker(marker);

            tempVehicleMarker = marker;

        }

 



Ayhan, 
  
 I have some advices to your JavaScript code, 
  
 1, “popup.show(LonLat);” and “popup.hide(LonLat)” is incorrect API in OpenLayers, both of them do not accept parameters. 
  
 2, The parameter “e.x” and “e.y” in the event is the offset position on the marker image which is not the right longitude and latitude. 
  
 3, “mouseover” is the event type to show the popup, oppositely, there should be a “mouseout” event to hide the popup, that’s why your popup always shows when you mouse hover on another object. 
  
 4, to maintain one popup is a good solution and popup.moveTo() helps you move popup’s position in the viewport. 
  
 If you still have some issue, please provide us a shortened sample which we can debug easily. 
  
 Thanks, 
 Howard

Thank you Howard,  
   
   I am not good with javascript ,I am learning through map suite. Yesterday I discovered "mouseout" event and I made with it, now it works. But I will try also popup.moveTo().  
  
   Thanks for your advise.

Ayhan, 
  
 You are welcome, moveTo is to update popup’s position in screen coordinate while you can call popup.updatePosition() after setting the lonlat of popup to update the position with world coordinate. 
  
 If you have any questions please let me know. 
  
 Thanks, 
 Howard