Sergio Palacio
Sergio Palacio

Reputation: 49

Google maps API marker refresh

I'm building a web site service for a GPS localisation service using a Syrus GPS modem. I have two files, one python code to catch the info coming from the modem and another HTML file which is the webpage, the python script rewrites directly to the HTML using:

 def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close

I realised that in order to update the marker in the map I have to update the whole webpage which is impractical.

I used an example from the google API site:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
    <script>
function initialize() {
var myLatlng = new google.maps.LatLng(21.0056,-75.8196);
  var mapOptions = {
    zoom: 15,
    center: myLatlng
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Diseno 201510'
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

    </script>

I'm just replacing the line with the latitude and longitude. So is there a simpler way to update the marker without refreshing the whole web page?

Upvotes: 2

Views: 1602

Answers (1)

carbon_ghost
carbon_ghost

Reputation: 1124

Yes. But I'm not sure how easy it's going to be because I'm not entirely sure how you're updating the map via Python in the first place. I.e. are you using websockets, re-rendering the template, etc...

When I was stuck doing the same thing, I used web sockets (specifically, socket.io) along with my Flask app. Every "x" mount of seconds, I send the updated Lat/Long coordinates to the site and use the map.panTo(coordinates) command to shift the map to the new coordinates without refreshing the page. Here's the javascript code I used to do that:

socket.on('newnumber', function(data){
    lat = data.number[0];
    lng = data.number[1];

    $('#locationText').text(data.number[3]);
    console.log("Lat: " + lat + " Long: " + lng);

    // Construct new LatLong Object 
    var myLatlng = new google.maps.LatLng(lng, lat);
    latLong = myLatlng;

    // Draw marker on the map 
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: data.number[3]
    });     
    // Move map to new coordinates w/o refreshing page
    map.panTo(latLong);
});

Upvotes: 2

Related Questions