Search code examples
javascriptphpgoogle-mapsmapspolyline

What is the correct format of saving Lat/Long coordinates into database and assign into path in javascript?


I'm trying to fetch the coordinates of a rout from my database which contains a set of lat/long strings.

Suppose I saved a path information (lat/lng) in my table by this format:

{lat:36.26479895658131,lng: 49.99473060839841},{lat:36.20609142498267,lng: 49.860834734374976},{lat:36.114064680113565,lng: 49.61570228808591}

Here is the code for preparing the above result:

<script>
var coordinates= [];
document.getElementById("field12").value = coordinates;

function myFunction(latLng) //latLng is comming from myFunction(e.latLng)
{
     var str = latLng;
     var res = String(latLng).split("(");
     var res1 = String(res).split(")");
     var res2 = String(res1).split(",");
     var final = "{lat:"+res2[1]+",lng:"+ res2[2]+"}";
     coordinates.push(final);
     document.getElementById("field12").value = coordinates;
}
</script>

Now I'm going to assign this coordinates into path in my java script code. Imagine I put the string of coordinates into a var like below:

var flightPlanCoordinates = [];

function RetrieveRouteCoordinates() {
    $.post('retrieveRouteCoordinates.php', function(data) {
        var myObj1 = JSON.parse(data);

        for(var t = 0; t < 2; t++)
        {
            if(myObj1[t] != null)
            {     
                flightPlanCoordinates[t] = myObj1[t].routCoordinates;
            }
        }
    });
}

And then, I set one of the path as an example like this:

poly.setPath(flightPlanCoordinates[0]);

Generally, I need to know is my coordinates format before inserting to database correct or not? if not show me the correct format of saving and then indicate how I can assign them into the poly.


Solution

  • Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

    example:

    <?php
    $a = 1.234; 
    $b = 1.2e3; 
    $c = 7E-10;
    ?>
    

    please check the documentation about the float numbers is explained here You can use number_format((float)$number, 14, '.', ''); To retrieve them

    for(var i = 0; i<location_array.length; i++)
        { var loc = location_array[i] ; //==>(12.77,  24.87)
    
            var split_arr1 = loc.split("(");
            var result_split_arr1 = split_arr1[1].split( ")" );
            var split_latLon = result_split_arr1[0];
     var latLng = new google.maps.LatLng(split_lat, split_lon);
            path.push(latLng)
            marker = new google.maps.Marker({
            position: latLng,
            map: map
            });
    }
    
        var flightPath = new google.maps.Polyline({
           path: path,
           strokeColor: "#FF0000",
           strokeOpacity: 1.0,
           strokeWeight: 2,
           map: map
        });
    
    }