使用两个不同表格中的值在一个Google地图上显示标记

时间:2016-03-31 11:44:22

标签: javascript php google-maps google-maps-api-3

这是我的代码。它从数据库表中读取纬度和经度,并将标记添加到地图上。我想要做的是在其中添加另一个表格,并根据相同地图上的纬度和经度值添加不同颜色的标记。我不知道如何从两个不同的表中获取纬度和经度,并在地图上显示不同颜色的标记。

function initialize() {
    <?php echo "initializing: ";?>
    var position = new google.maps.LatLng(39.40233290,77.89265660 );
    var image = {
        url: 'images/image.png',
        // This marker is 20 pixels wide by 32 pixels high.
        size: new google.maps.Size(30, 32)
    };

    var myOptions = {
        zoom: 10,
        center: position,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    <?php       
    $sql="select latitude,longitude FROM coffeeshop ";
    $records = mysql_query($sql, $conn);
    if (!$records) {
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        exit;
    }

    while($row = mysql_fetch_assoc($records)) {
        ?>
        var lat= <?php echo $row['latitude'] ?>;
        var long=<?php echo $row['longitude'] ?>;
        addMarker(lat,long);
        <?php echo $row['longitude'];
    }
    ?>

    var geocoder = new google.maps.Geocoder;
    var infowindow = new google.maps.InfoWindow;  

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        title:"This is the place."
    });  

    var marker2 = new google.maps.Marker({
        position: position,
        map: map,
        icon: image,
        title:"This is the place."
    });  

    var contentString = 'Hello <strong>World</strong>!';
    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map,marker);
        geocodeLatLng(geocoder, map, infowindow);
    });

    google.maps.event.addListener(marker2, 'click', function() {
        infowindow.open(map,marker2);
        geocodeLatLng(geocoder, map, infowindow);
    });

    function addMarker(lat,long) {
        var latlongMarker = new google.maps.LatLng(lat,long);

        var marker = new google.maps.Marker({
            position: latlongMarker, 
            map: map,            
        }); 

        var marker2 = new google.maps.Marker({
            position: latlongMarker, 
            map: map,
            icon:image,            
        }); 

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
            geocodeLatLng(geocoder, map, infowindow,marker);     
        });
    }    
}

1 个答案:

答案 0 :(得分:0)

我建议你使用ajax来获取没有mysql函数的值。

使用ajax,您可以从某些php方法获取数据。此方法可以收集db所需的所有数据(在您的情况下来自两个表)并将其准备为一个数组(您必须将其编码为json以通过ajax获取它)。

此外,代码将更加清晰,因为您不会使用javascript来破坏php。