简体   繁体   中英

get user-specified values into javascript file

I have a google maps application in which map settings are defined in a js file (map.js) as follows:

function initialize() {
        var latlng = new google.maps.LatLng(42.133633, -11.469928);
        var myOptions = {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

My home page (index.php) calls this script. I'd like to let users specify latitude, longitude, zoom level and map type. To this end I've created a form (setMap.htm), a client-side validation script (setMap.js), and setMap.php, which validates and sanitizes user input.

However, I'm not clear on how to get user-specified values into map.js. Could I use ajax in map.js?:

function loadData(){

    $.getJSON('setMap.php', . . . . ?

And how do I replace the hardcoded values in function initialize() with the results of this call?

Do I need an ajax call in setMap.php as well?

You can do it in many ways. One you just posted: http://api.jquery.com/jquery.getjson/

$.getJSON( "setMap.php", function( data ) { // Do something here });

Your setMap.php just have to return valid json data.

You can also echo data straight into js value during request: echo 'var = {some data}' but I think it's not "nice" solution.

One more option is: don't use server side part. Just fetch data from form using JS, validate it and use without php reprocessing (if you don't need to save it somewhere you actually don't need to validate it on the server side)

https://developers.google.com/maps/documentation/javascript/reference?csw=1 You should have

var map = google.maps.Map();
map.setOptions({your_options});

So you just fetch options from your form and fix map options in flight with no page reload or ajax request.

// html
<input id="zoom" type="text" />

// js code
var map;
function initialize() {
        var latlng = new google.maps.LatLng(42.133633, -11.469928);
        var myOptions = {
            zoom: 13,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };
        map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
}
function update() {
        var options = {};
        options.zoom = $('input#zoom').val();
        map.setOptions{options};
}

BUT PLEASE! This is just not tested pseudocode!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM