1

I have a clunky-architecture question :)

I have 1 php script. The script performs a database query for longitude/latitude from the database, and gets that data. Then what I need it to do is call JavaScript function which places a marker on the spot of the lat/lng.

Is that possible to accomplish? How is such a thing best done?

Thanks, Alex

2 Answers 2

2

A simplest way to pass value from php to javascript is to simply create a variable inside script tag on your page.

<script type="text/javascript">
    var lat = <?php echo $phpLat;?>;
    var lng = <?php echo $phpLng;?>;

    ...
</script>    

Then, where you initialize the map, you can also create a marker. Something like this

var point = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
    position: point,
    title: 'test'
});
marker.setMap(map);

You can check Google Maps Javascript API documentation for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

you may want to use actual php tags around the javascript variables: <?php echo $phpLat;?>
@Endophage Thanks for correction. I don't work with PHP and so wasn't sure how scripts are opened in there.
No problem. There are templating systems that would parse the file and could use markers as you did.
0

You could use the jQuery library to do this by using the ajax function.

this way you use the javascript to run the PHP this is the easiest way.

$.ajax({ url: "your-php-file.php", success: function(result){ //the return will be in the result variable } });

it's up to you how you return it from php but you could return it as an array, comma delimited string, etc...

2 Comments

If you already have the data when you're initially building the page, making a second call to get it is an unnecessary time waster and added complexity. Ajax calls should only be used when you have to load some piece of data you don't know on the initial load (like something determined by user input/action)
I meant for him to do it as an ajax call from the beginning, my answer clearly says this...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.