0
votes

I am looking for a way to add markers on to a map which I have created in a web page... Here is the code for the page...

<link href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css' rel='stylesheet' />
<script src='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.js'></script>

<style>
    #map {
        width: 100%;
        height: 600px;
    }
</style>

<div id='map' />

<script type='text/javascript'>
    var map = L.mapbox.map('map', '[mapname]')

</script>

This renders the map from mapbox - but I cannot figure out how to write a web service to provide the markers. This data is stored in a table in a SQL database.

I understand that I can load a GeoJSON file with the data in - but I am unsure on how to create this file - and how it differs from regular JSON - any help would be grateful!

Thanks

2
GeoJSON is just JSON that uses a specific structure.Andy

2 Answers

0
votes

I don't know GeoJSON, but this is how you handle it using the Google Maps v3 API:

For one marker:

        lng = (4.502384184313996, 4.461185453845246);
        lat = (51.011527400014664, 51.02974935275779);
        cur_loc = new google.maps.LatLng(lat, lng);

        var marker = new google.maps.Marker({
            position: cur_loc, //To be defined with LatLng variable type
            draggable: false, 
            animation: google.maps.Animation.DROP,
            icon: image
        });

        // To add the marker to the map, call setMap();
        marker.setMap(map);

For multiple markers retrieved from MySQL (Ajax):

        google.maps.event.addListener(map, 'idle', function () {
            var bounds = map.getBounds();
            var ne_lat = bounds.getNorthEast().lat();
            var ne_lng = bounds.getNorthEast().lng();
            var sw_lat = bounds.getSouthWest().lat();
            var sw_lng = bounds.getSouthWest().lng();
            // Call you server with ajax passing it the bounds
            $.ajax({
                  type: "GET",
                  url: "http://www.zwoop.be/develop/home/bars/bars_get_markers.php",
                  data: {
                      'ne_lat': ne_lat,
                      'ne_lng': ne_lng,
                      'sw_lat': sw_lat, 
                      'sw_lng': sw_lng
                  },
                  datatype: "json",
                  success: function(data){
                    if(data){
                        // In the ajax callback delete the current markers and add new markers
                        function clearOverlays() {
                            for (var i = 0; i < array_markers.length; i++ ){
                                array_markers[i].setMap(null);
                            }
                            array_markers = [];
                        };
                        clearOverlays();

                        //parse the returned json obect
                        //Create a marker for each of the returned objects                        
                        var obj  = $.parseJSON(data);
                        $.each(obj, function(index,el) {
                            var bar_position = new google.maps.LatLng(el.lat, el.lng);
                            image_bar = "http://www.sherv.net/cm/emoticons/drink/whiskey-smiley-emoticon.gif";

                            var marker = new google.maps.Marker({
                                position: bar_position,
                                map: map, 
                                icon: image_bar
                                });
                            //Add info window. With HTML, the text format can be edited. 
                            google.maps.event.addListener(marker, 'click', function() {
                                if (infowindow){
                                    infowindow.close();
                                };
                                content = "<div id='infowindow_container'><h3><a class='profile_name_bar' href='#' id='" + el.profile_id + "'>"+el.profile_name+"</a></h3></div>";
                                infowindow = new google.maps.InfoWindow({ 
                                    content: content
                                });
                                infowindow.open(map,marker);
                            });                            
                            array_markers.push(marker);
                        });

                        //Place the markers on the map
                        function setAllMap(map) {
                          for (var i = 0; i < array_markers.length; i++) {
                            array_markers[i].setMap(map);
                          }
                        }
                        setAllMap(map);

                        //marker clusterer
                        var zoom = 17;
                        var size = size ==-1?null:size;
                        var style = style ==-1?null:style;
                        var markerCluster = new MarkerClusterer(map, array_markers,{maxZoom:zoom,gridSize:size});
                    }
                },
                  error: function (xhr, ajaxOptions, error) {
                        alert(error);
                        }
                    })             
          });

This code looks at the viewport of the map and loads the markers dynamically. When you zoom / pan, the code will query the database: the LatLng coordinates of the map bounds are sent to the server and the marker coordindates that are found in the database are returned from the Ajax call. The marker coordinates are loaded into an array at the client and written on the map. I used the marker clusterer to avoid crowded markers.

I hope this helps. I don't know the benefits of the plugin that you are using though.

0
votes

I'm doing something similar, this is where I'm up to.

I use PHP to get the coordinates from the MySQL database and return something like this:

var geoJson = [
    {
        type: 'Feature',
        "geometry": { "type": "Point", "coordinates": [-77.03, 38.90]},
        "properties": {}
    },
    {
       type: 'Feature',
       "geometry": { "type": "Point", "coordinates": [-64.567, 32.483]},
       "properties": {}
    }      
];

The PHP file looks something like this:

<?php  
            // Connect
            $link = mysqli_connect("[host]","[username]","[password]","[database-name]") or die("Error " . mysqli_error($link));

            // Get the coordinates of the places
            $query = "SELECT * FROM `places`";
            $places = $link->query($query);

                var geoJson  = [<?php

                // Loop through places and plot them on map 

                // This is just building the JSON string

                $i = 1;
                while($venue = $venues->fetch_assoc()): 

                    if($i > 1){ echo ","; } ?>
                    {
                        type: 'Feature',
                        "geometry": { "type": "Point", "coordinates": [<?php echo $venue['lon']; ?>, <?php echo $venue['lat']; ?>]},
                        "properties": {}
                    }

                    <?php $i++; ?>

                <?php endwhile; ?>

            ];




            map.markerLayer.setGeoJSON(geoJson);

Note - This PHP is inside the Javascript that is making the map.

Like I said its early days for me as well. The code above works, but its just as far as I've got so far. The next thing I'm going to look at is JavaScript templates and using them to pull in the data that way. I have a feeling that will be a better way but I'm not sure. Anyway maybe that's useful to you, let me know if you get any further with it :)