Display coordinates on map with Gmap

Asked

Viewed 500 times

0

I want to get coordinates from the database and show them on the map along with the marker, but I can’t. I think something is missing from the view. It should show only the last location data stored in the BD.

Can anyone help me? The problem is that it searches the data in the Bank, and if I manually enter the coordinates the map shows. So I guess it’s no mistake with the API key, but if I try to search from the class gadoBean he does not seek.

Follows code:

View:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui">
<h:head>
<script src="https://maps.googleapis.com/maps/api/js?Sensor=false"
type="text/javascript"></script>
</h:head>
<title>Rastreamento</title>
<h:body>
 <h:form>
   <p:poll interval="10"
           listener="#{gadoBean.obterPosicaoTag}"
           update="panelMap"/>
<p:panel id="panelMap">
<p:gmap id="mapa"  

        center="#{gadoBean.center}" 
        zoom="18" 
        model="#{gadoBean.mapa}"  
        type="HYBRID" 
        style="width:600px;height:400px"/>
    </p:panel>
    </h:form>  
</h:body>
</html>

Gadobean:

package com.sisRastrbov.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.inject.Named;

import com.sisRastrbov.model.Coordenadas;
import com.sisRastrbov.model.Fazenda;
import com.sisRastrbov.model.Gado;
import com.sisRastrbov.model.Tag;
import com.sisRastrbov.model.Usuario;
import com.sisRastrbov.repository.CoordenadasRep;
import com.sisRastrbov.repository.Usuarios;
import com.sisRastrbov.repository.fazendasRep;
import com.sisRastrbov.security.AuthenticationService;
import com.sisRastrbov.services.CoordenadasService;

import org.primefaces.model.map.Circle;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;

@Named
@ViewScoped
public class GadoBean implements Serializable {

private static final long serialVersionUID = 1L;
private MapModel mapa;
private Marker marcador = null;
private Circle circulo = null;
private Tag tag;
private Gado gadoAtual;
private float lastLat, lastLong;
private Coordenadas coordenadas;
private List<Coordenadas> posicoes;
private Fazenda fazendaAtual;
private List<Fazenda> fazendas;
private Usuarios usuarios;
private String center;


@Inject
private CoordenadasService coordenadasService;

@Inject
private CoordenadasRep coordenadasRep;

public String getCenter() {
    return center;
}

public void setCenter(String center) {
    this.center = center;
}

private void limpar() {
    coordenadas = new Coordenadas();

}
//<p:commandButton value="Rastrear" id="botaoRastrear" action="# {gadoBean.obterPosicaoTag}" update="mapa"/>
public GadoBean(){
    mapa = new DefaultMapModel();
}
public void inicializar() {

}

public void salvar() {

    coordenadasService.salvar(coordenadas);
    limpar();

}
public void obterPosicaoTag() {
    posicoes = new ArrayList<Coordenadas>();
    posicoes = coordenadasRep.listar();
    int totalPosicoes = this.getPosicoes().size(); //obtem o total de   registros contidos na tabela Coordenadas.
    if (totalPosicoes > 0) {
        Coordenadas posicaoAtual = this.getPosicoes().get(totalPosicoes -  1);//posicao atual recebe sempre a última posição registrada
        LatLng coord = new  LatLng(posicaoAtual.getPosLongitude(),posicaoAtual.getPosLatitude());//coord  recebe o ponto.
        lastLong =(float)posicaoAtual.getPosLongitude();//recebem as coordenadas.
        lastLat = (float)posicaoAtual.getPosLatitude();
        center = lastLat + "," + lastLong;


        System.out.println(center);

        if (circulo == null) {//cria um circulo verde em volta do ponto 
            circulo = new Circle(coord, 15);
            circulo.setStrokeColor("#00ff00");
            circulo.setFillColor("#00ff00");
            circulo.setStrokeOpacity(0.5);
            circulo.setFillOpacity(0.5);
            mapa.addOverlay(circulo);
        } else {
            circulo.setCenter(coord);
        }
        if (marcador == null) {
            marcador = new Marker(coord);
            mapa.addOverlay(marcador);
        } else {
            marcador.setLatlng(coord);
        }

    } else {
        tag = null;
    }
}

public Marker getMarcador() {
    return marcador;
}

public MapModel getMapa() {

    return mapa;
}

public void setMapa(MapModel mapa) {
    this.mapa = mapa;
}

public Fazenda getFazendaAtual() {
    return fazendaAtual;
}

public void setFazendaAtual(Fazenda fazendaAtual) {
    this.fazendaAtual = fazendaAtual;
}

public void setMarcador(Marker marcador) {
    this.marcador = marcador;
}

public Circle getCirculo() {
    return circulo;
}

public void setCirculo(Circle circulo) {
    this.circulo = circulo;
}

public Tag getTagAtual() {
    return tag;
}

public void setTagAtual(Tag tagAtual) {
    this.tag = tagAtual;
}

public float getLastLat() {
    return lastLat;
}

public void setLastLat(float lastlat) {
    this.lastLat = lastlat;
}

public float getLastLong() {
    return lastLong;
}

public void setLastLong(float lastlong) {
    this.lastLong = lastlong;
}

public List<Coordenadas> getPosicoes() {
    return posicoes;
}

public void setPosicoes(List<Coordenadas> posicoes) {
    this.posicoes = posicoes;
}
public Coordenadas getCoordenadas() {
    return coordenadas;
}

public void setCoordenadas(Coordenadas coordenadas) {
    this.coordenadas = coordenadas;
   }




}

Coordinates:

    package com.sisRastrbov.model;

    import java.io.Serializable;

    import java.util.Date;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    @Entity
    @Table(name = "Coordenadas")
    public class Coordenadas implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;
    // Gado gado_id;
    private double posLatitude;
    private double posLongitude;
    private Date posData;
    private Tag tag;



    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToOne
    @JoinColumn(name = "tag_id", nullable = false)
    public Tag getTag() {
        return tag;
    }

    public void setTag(Tag tag) {
        this.tag = tag;
    }

    /*@ManyToOne
    @JoinColumn(name = "gado_id", nullable = false)
    public Gado getGado_id() {
        return gado_id;
    }*/

    /*public void setGado_id(Gado gado_id) {
        this.gado_id = gado_id;
    }*/

    @Column(name = "pos_latitude")
    public double getPosLatitude() {
        return posLatitude;
    }

    public void setPosLatitude(double posLatitude) {
        this.posLatitude = posLatitude;
    }
    @Column(name = "pos_longitude")
    public double getPosLongitude() {
        return posLongitude;
    }

    public void setPosLongitude(double posLongitude) {
        this.posLongitude = posLongitude;
    }

    @Column(name = "pos_data")
    public Date getPosData() {
        return posData;
    }

    public void setPosData(Date posData) {
        this.posData = posData;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Coordenadas other = (Coordenadas) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
   }

Tag:

package com.sisRastrbov.model;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;




@Entity
@SequenceGenerator(name = "tag_sequence", sequenceName = "tag_sequence")
@Table(name = "tag")
public class Tag implements Serializable {

private static final long serialVersionUID = 1L;

private Long tagId;
private char tagStatus;
private String descricao;

List<Coordenadas> posicoes;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =  "tag_sequence")
@Column(name = "tag_id")
public Long getTagId() {
    return tagId;
}

public void setTagId(Long tagId) {
    this.tagId = tagId;
}

@Column(name = "tag_status")
public char getTagStatus() {
    return tagStatus;
}

public void setTagStatus(char tagStatus) {
    this.tagStatus = tagStatus;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((tagId == null) ? 0 : tagId.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Tag other = (Tag) obj;
    if (tagId == null) {
        if (other.tagId != null)
            return false;
    } else if (!tagId.equals(other.tagId))
        return false;
    return true;
}

public String getDescricao() {
    return descricao;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}
@OneToMany(mappedBy = "tag")
public List<Coordenadas> getPosicoes() {
    return posicoes;
}

public void setPosicoes(List<Coordenadas> posicoes) {
    this.posicoes = posicoes;
}

}

Coordinatorssrep:

package com.sisRastrbov.repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import com.sisRastrbov.model.Coordenadas;



public class CoordenadasRep implements Serializable{
private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;

public Coordenadas guardar(Coordenadas coo) {
    return coo = manager.merge(coo);
}



public List<Coordenadas> listar(){
    List<Coordenadas> coords = new ArrayList<Coordenadas>();
    coords = manager.createQuery("from Coordenadas",   Coordenadas.class).getResultList();
    return coords;
}
}

1 answer

0

Can you tell if the coordinate is correct?

What I noticed is that the center="#{gadoBean.center}" should contain Latitude and Longitude.

Example:

center="#{meuBean.latitude}, #{meuBean.longitude}"

Where:

private BigDecimal latitude;  
private BigDecimal longitude;

Treco no Primefaces

<p:gmap center="#{meuBean.latitude}, #{meuBean.longitude}" zoom="13" type="HYBRID" styleClass="ms-mapas" model="#{meuBean.mapa}" />

Excerpt from JS

<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
  • Thanks for your attention Marcelo. I tried this way your example, also did not work. The variables latitude and longitude are float. Can’t you? I think it’s the error in the view, can you give me a hand? I didn’t post the API key, but I’m using it like this: <script src="https://maps.googleapis.com/maps/api/js?key=keyminha key" type="text/javascript"></script> I’m forgetting to initialize something?

  • I edited and put the specifications as I use here.

  • I noticed that you use https and I http as well as different addresses.

  • put the address the same as yours, put sensor=true, sensor=false, put the API key and nothing...

  • The map turns black with several messages written: we have no images from here. But the location data is from a point where the satellite covers..

  • Usually when it turns black is that the location is wrong.

  • So, but if you put them in manually without pulling from my cow classBean he shows you, you’ll understand.. does that have to have something in my constructor, some initialization of variables..

  • From a System.out.println() with the coordinates in the get deo Gadobean and see what is returning.

  • returns latitude and normal longitude

  • I did some tests and it worked shows the black screen when I reversed the coordinates or they were wrong. I don’t know what else to do.

  • Beauty Marcelo, thanks! I’ll try here, if I can put here

  • Now he’s loading the map, I think it was the wrong location. But I still couldn’t place the marker...

  • That is something else. I suggest closing this call and opening another.

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.