I have a google map on my website created in codeigniter. Now I want to move the markers with data from my sql database. The data in my database will be updated. I can draw markers on the map by biostall. Now I want to move them.
So I load all the markers and pass them to my view to draw them with a ajax/javascript script. I get no errors but also no markers.. I'm not a pro in ajax and javascript so the problem needs to be there but I can't fix it.. Here's my code. The map should be updated each 3 seconds.
My controller :
function render_maps() {
$userid = $this->uri->segment(3);
$userlevel = $this->user_model->get_user_level($userid);
if ($userlevel > 2) {
$this->load->library('googlemaps');
$this->googlemaps->initialize();
#$this->marks();
$config['zoom'] = 'auto';
$data['map'] = $this->googlemaps->create_map();
$data['markers'] = json_encode($this->user_model->get_marks());
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
$this->load->view('dashboard_maps', $data);
$this->load->view('wrapper', $data);
}
}
My view :
<head>
<?php echo $map['js']; ?>
<script type="text/javascript">
function refreshMarkers() {
$.ajax({
url: "<?php site_url('User/render_maps/'. $this->session->userdata('user_id')) ?>",
type: "POST",
data: ({value: $markers}),
dataType: "json", //retrieved Markers Lat/lng in Json, thus using this dataType
success: function(data){
//Removing already Added Markers//////////
for (var i = 0; i < $markers.length; i++) {
$markers[i].setMap(null);
}
$markers = new Array();
//////////////////////////////////////////
// Adding New Markers////////////////////
for (var i = 0, len = data.length; i < len; ++i) { // Iterating the Json Array
var d = data[i];
var lat = parseFloat(d.lat);
var lng = parseFloat(d.lng);
var myLatlng = new google.maps.LatLng(lat, lng);
var marker = {
map: map,
position: myLatlng // These are the minimal Options, you can add others too
};
createMarker(marker);
}
}
}
);
</script>
Your function refreshMarkers() is missing a closing } bracket. Please also include all dependencies such as jquery and other functions.
You don't have to be a pro in ajax or javascript to achieve that. Make sure you retrieve the data successfully using your browser's console.
Here's a vanilla example for Google Map JS API with multiple markers which shows different earthquake locations. Try running the code snippet below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
</head>
<body>
Click Here >> <button id="earthquakes">Show Earthquakes</button>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDrhmCE5YeH0r9Kkeq-v4ZXBd87UvwCOrw&callback=initMap">
</script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 4.8259171, lng: 63.3691405},
zoom: 1
});
}
function createMarker(latlng, name) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name
});
}
function displayMarkers() {
console.log('displayMarkers:'+latitd+':'+longtd+'\n');
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
var latitd;
var longtd;
var titleName;
var nowDate = new Date();
var displayDate = nowDate.toJSON().slice(0,10);
nowDate.setDate(nowDate.getDate() - 1);
var yesterDate = nowDate.toJSON().slice(0,10);
$(document).ready(function() {
$('#earthquakes').click(function() {
getQuakes();
});
function getQuakes() {
console.log('yesterDate:'+yesterDate+', displayDate:'+displayDate+'\n');
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
dataType : 'json'
})
.done(function(data) {
console.log('data.features:'+data.features);
$.each(data.features, function(key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
displayMarkers();
});
})
.fail(function(e){
console.log(e);
})
.always(function(){
console.log('ajax executed');
});
}
});
</script>
</body>
</html>
Related
I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"
This is my code, When i am calling removeMarkers(), it's not removing the markers.
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
// push object into features array
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
//icon: icons[feature.type].icon,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
This is my full code. For displaying places(church) that which i saved in my database along the route from origin to destination. If i changed the origin and destination i want to remove old markers and displaying new markers without refreshing the page.
css
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
html
<div id="map" height="460px" width="100%"></div>
<input type="text" id="distance" value="3" size="2">
<input type="text" id="from" />to
<input type="text" id="to" />
<input type="submit" onClick="route()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=api_ key&libraries=places"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/routeboxer/src/RouteBoxer.js" type="text/javascript"></script>
javascript
<script>
var map;
var marker;
var infowindow;
var messagewindow;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var coordinates=null;
var features = [];
var gmarkers = [];
<?php
echo "
var lat={$lat};
var lng={$lng};
"
?>
function initialize() {
var location = {lat: 10.525956868983068, lng:76.21387481689453};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 13
});
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
}
function route() {
removeMarkers()
clearBoxes();
distance = parseFloat(document.getElementById("distance").value) * 0.1;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 0,
map: map
});
}
}
function findPlaces(searchIndex) {
var request = {
bounds: boxes[searchIndex],
};
coordinates = boxes[searchIndex].toString().match(/[0-9]+\.[0-9]+/g);
$.ajax({
url:"http://localhost/church_finder/index.php/MapController/search_church",
type:'POST',
data:{coordinates:coordinates},
//dataType:'json',
success: receiver
});
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else {
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
}
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function receiver(data, textStatus, XMLHttpRequest) {
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
var lat = json[i]["lat"];
var lng = json[i]["lng"];
features.push({ position: new google.maps.LatLng(lat,lng) });
}
features.forEach(function(feature) {
var marker1 = new google.maps.Marker({
position: feature.position,
map: map
});
});
gmarkers.push(marker1);
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
enter image description here
function removeMarkers(){
features.length=0;
if (gmarkers != []) {
for(var i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
gmarkers =[];
}
Your app throws loads of errors in the console and this is just a temporary fix to what you are asking for:
change the origin and destination, I want to remove old markers and
displaying new markers without refreshing the page
call your initialize() function with a script tag in your HTML file. This is where you include your API key for the project:
<script defer async src="https://maps.googleapis.com/maps/api/js?
key=YOUR_KEY&callback=initialize">
Where is the map element passed in the map constructor?
Create a div element in your HTML to contain the map and add CSS style to it
#map {
height: 100%;
}
html, body {
margin: 0;
padding: 0;
height: 100%;
}
This is actually in the Google Maps API documentation;
Always set the map height explicitly to define the size of the div
element that contains the map.
Now into your JS code...
What are you using var service for? var service is firstly declared in the global scope with a null value and then assigned to a PlacesService constructor...but service is not defined simply because you have not included the places library in your script tag:
ADD PLACES LIBRARY IF YOU WANT TO USE PLACES API
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY&_ADD_libraries=places_PLEASE_"></script>
Because var service cannot be run, just remove it (it actually does not do anything but adding lines in your code right now) along with the RouteBoxer()
REMOVE THESE LINES - THEY ARE USELESS RIGHT NOW
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
If you do this, without refreshing the page, you clear the markers for each subsequent requests. You get loads of errors still because you have both syntax and logic bugs in your app.
Get a BIN here
I want to be able to click on a marker or a city name and pop-up the info.window for that specific marker
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Magic Towns of Mexico</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/styles.css">
<style>
html,
body {
font-family: Arial, sans-serif;
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="menuContainer">
<span class="center" style="font-size:30px;cursor:pointer" onclick="openNav()">☰</span>
<div id="mySidenav" class="sidenav alignTextCenter">
×
<h1>Locations:</h1>
<form role="search">
<input type="text" data-bind="value: query, valueUpdate: 'keyup'" placeholder="Search...">
</form>
<div data-bind='with: currentPlace' >
<div data-bind='foreach: filteredPlaces' class="alignTextCenter">
<p href="#" class="whiteFont" data-bind='text: city, click: clickSelection'></p>
</div>
</div>
</div>
</div>
<script src='js/sidebar.js'></script>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/knockout-3.4.2.js"></script>
<script src="js/data.js"></script>
<script src="js/app2.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=geometrykey=AIzaSyBnwbuI0b5q6p5sJAa2wcHIy2DGkZFisBY&v=3&callback=initMap">
</script>
</body>
</html>
JavaScript:
var initialPlaces = [
{"city":"Tepotzotlán","lat":19.7185096,"lng":-99.2065202},
{"city":"Valle de Bravo","lat":19.1950964,"lng":-100.1326725},
{"city":"Cuitzeo","lat":19.9685057,"lng":-101.1406046},
{"city":"Pátzcuaro","lat":19.5134498,"lng":-101.6091554},
{"city":"Sta. Clara del Cobre","lat":19.4064279,"lng":-101.639697899999},
];
var map, google;
var markers = [];
var wikiElem;
var Place = function(data) {
this.city = ko.observable(data.city);
this.lat = ko.observable(data.lat);
this.lng = ko.observable(data.lng);
};
var ViewModel = function() {
var self = this;
self.placeList = ko.observableArray([]);
self.query = ko.observable(''),
initialPlaces.forEach(function(placeLocation) {
self.placeList.push( new Place(placeLocation));
});
self.currentPlace = ko.observable( this.placeList()[0]);
// Populate infowindow
this.populateInfoWindow = function(marker, infoWindow) {
if (infoWindow.marker != marker) {
infoWindow.marker = marker;
var $wikiElem = '';
var cityStr = marker.city;
var wikiUrl = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' +
cityStr + '&format=json&callback=wikiCallback';
var wikiRequestTimeOut = setTimeout(function() {
$wikiElem = 'failed to get wikipedia resources';
}, 8000);
$.ajax({
url: wikiUrl,
dataType: "jsonp",
success: function(response) {
var articleList = response[1];
for (var i = 0; i < articleList.length; i++) {
articleStr = articleList[i];
var url = 'http://en.wikipedia.org/wiki/' + articleStr;
$wikiElem += '<li>' + articleStr + '</li>';
}
infoWindow.setContent(self.titleContent + '<hr>' + self.wikiTitle + $wikiElem);
clearTimeout(wikiRequestTimeOut);
}
});
self.wikiTitle = '<h3>Relevant Wikipedia Links</h3>';
self.titleContent = '<div>' + marker.city + '<div>';
infoWindow.open(map, marker);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
marker.setAnimation(null);
}, 1500 );
// Cleared infowindow if is closed
infoWindow.addListener('closeclick', function() {
infoWindow.marker = null;
});
}
};
// Handles click selection on map and list
self.clickSelection = function() {
self.populateInfoWindow(this, self.largeInfoWindow);
};
// Construct Map
self.initMap = function() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 24.3001235, lng: -102.2718002},
zoom: 5,
});
var largeInfoWindow = new google.maps.InfoWindow();
// Create array for markers
for (var i = 0; i < initialPlaces.length; i++) {
this.city = initialPlaces[i].city;
this.lat = initialPlaces[i].lat;
this.lng = initialPlaces[i].lng;
// create a marker per city
this.marker = new google.maps.Marker({
map: map,
position: {lat: this.lat, lng: this.lng},
city: this.city,
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5
},
animation: google.maps.Animation.DROP,
});
// Push the marker to our array of markers.
this.markers.push(this.marker);
this.marker.addListener('click', self.clickSelection);
}
};
self.filteredPlaces = ko.computed(function() {
if (!self.query()) {
return self.placeList();
} else {
return self.placeList()
.filter(place => place.city().toLowerCase().indexOf(self.query().toLowerCase()) > -1);
}
});
};
ko.applyBindings(ViewModel);
I would like to be able to click on the marker an populate the info.window, as well if I click on the list I want to populate the info.window.
The result I have right now is this error:
Uncaught TypeError: Cannot read property 'marker' of undefined
at ViewModel.populateInfoWindow (app2.js:24)
There are multiple problems with this code.
First of all, the script reference to google maps api has an error. It should have &key instead of geometrykey & is because they are separate parameters.
https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyBnwbuI0b5q6p5sJAa2wcHIy2DGkZFisBY&v=3&callback=initMap
Next, your callback function doesn't exist. So I created it.
function initMap() {
var viewmodel = new ViewModel();
viewmodel.initMap();
}
This line in the initMap method needs to change:
var largeInfoWindow = new google.maps.InfoWindow();
Using var in JavaScript creates a new local variable. largeInfoWindow is local to the scope of initMap. In order to make it visible outside that scope replace it with this.
self.largeInfoWindow = new google.maps.InfoWindow();
I changed your http:// wikipedia api calls to https:// if you are accessing your site through http:// . However, if you're accessing your site through http you can leave this alone.
In the future it might be easier to use jsFiddle (or something similar such as codepen or pastebin).
I'm building something with Google Maps and Instagram. I'm trying to send the coordinates of the Instagram photos from my PHP file to my JavaScript file using AJAX. I basically have no idea how to handle this on the JavaScript side.
This is what my index.php file looks like:
<?php
$jsonText= file_get_contents("");
$instagram = json_decode($jsonText);
foreach ($instagram->data as $photo) {
$longitude = $photo->location->longitude;
$latitude = $photo->location->latitude;
$picture = $photo->images->thumbnail->url;
$results = array($latitude, $longitude, $picture);
echo json_encode($results, true);
}
?>
My js file looks like this:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.525961, 15.255119)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.ajax({
url: 'index.php',
dataType: 'json',
success: function(data) {
var location = new google.maps.LatLng();
var marker = new google.maps.Marker({
position: location,
map: map,
title:"Where the photo was taken.."
});
}
})
}
First of all, I would suggest you not to share your API Key/Access Token publicly.
I made slight changes to your code. This is the ajax call now,
$.ajax({url: 'test.php'}).done(function(data) {
// alert(data);
for (var i = data.length - 1; i >= 0; i--) {
for (var j = data[i].length - 1; j >= 0; j--) {
$("#someElement").append(data[i][j]);
};
};
}
);
You can use the data as you wish.
I have this code that selects the type of a restaurant. After selecting any type the page is refreshed and after some SQL processing I get all restaurants corresponding to the selected type and show it in Google Maps.
How can I do that without refreshing the complete page, like only refreshing the <div> containing Google Maps?
<select class="mapleftS" name="type" id="type" onchange="changeType(this.value)">
<option value="0">كل الانواع</option>
<?$type = mysql_query("select * from rest_type ");
while($rod = mysql_fetch_array( $type )) {
if($rod[id] == $_REQUEST['type'])
$selll = 'selected';
else {$selll = '';
?>
<option value="<?=$rod[id]?>" <?=$selll?> ><?=$rod[name]?></option>
<? } ?>
</select>
<script>
function changeType( id ) {
parent.location = '?type=' + id;
}
$(function() {
var text_menu = $("#type option:selected").text();
$("#ddddd_").html(text_menu);
});
</script>
After selection this code is run:
if($_REQUEST['type']) {
// do some thing and refrsh map div
} else {
// do some thing and refrsh map div
}
And the following element contains Google Maps:
<div id="mppp" class="map"></div>
JS for Google Maps:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&sensor=true"></script>
<script type="text/javascript">
var address_index = 0, map, infowindow, geocoder, bounds, mapinfo, intTimer;
$(function (){
mm();
});
mm = function() {
// Creating an object literal containing the properties you want to pass to the map
var options = {
zoom: 15,
center: new google.maps.LatLng(24.701564296830245, 46.76211117183027),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
map = new google.maps.Map(document.getElementById('mppp'), options);
infowindow = new google.maps.InfoWindow();
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
//******* ARRAY BROUGHT OVER FROM SEARCHRESULTS.PHP **********
mapinfo = [ <?=$da?> ];
intTimer = setInterval("call_geocode();", 300);
}
function call_geocode() {
if( address_index >= mapinfo.length ) {
clearInterval(intTimer);
return;
}
geocoder.geocode({
location: new google.maps.LatLng(mapinfo[address_index][6], mapinfo[address_index][7])
}, (function(index) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Scale our bounds
bounds.extend(results[0].geometry.location);
var $id = mapinfo[index][0];
var $tell = mapinfo[index][3];
var $title = mapinfo[index][2];
var $img_src = mapinfo[index][3];
var img_src = mapinfo[index][1];
var $logo = mapinfo[index][4];
var $status = mapinfo[index][5];
var $sell = mapinfo[index][6];
var $city = mapinfo[index][8];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapinfo[index][6], mapinfo[index][7]),
icon: {
url : '<? bloginfo('url'); ?>' + img_src + '',
scaledSize : new google.maps.Size(50,50)
},
map: map,
scrollwheel: false,
streetViewControl: true,
title: $title
});
google.maps.event.addListener(marker, 'click', function() {
// Setting the content of the InfoWindow
if (img_src) {
var imdd = '<img src="<? bloginfo('url'); ?>' + img_src + '" width="60" height="60" style="margin-left:4px;float:right;" />';
}
else {
var imdd = '';
}
if ($tell) {
var tell = 'رقم الهاتف : '+$tell+'<br>';
}
else {
var tell = '';
}
if ($status) {
var status = 'الحي : '+$status+'<br>';
}
else {
var status = '';
}
if ($city) {
var city = 'المدينة : '+$city+'<br>';
}
else {
var city = '';
}
var content = '<div id="info" style="direction:rtl;font:15px time new roman;font-weight:bolder;position:relative;width:210px;"><div style=" font-size:13px;font-family:Tahoma;font-weight:bolder;text-align:center;font-weight:bold">' + $title + '</div><br><div style="float:right">' + imdd + '</div><div style="float:right;text-align:right;font-family:Tahoma">' + tell + city + status + '</div><br /><a style="float:left;color:#d22f00;font-size:12px;font-family:Tahoma" href="<? bloginfo('url'); ?>/rest-det/?id=' + $id + '">المزيد+</a></div>';
infowindow.setContent(content);
infowindow.open(map, marker);
});
map.fitBounds(bounds);
if (mapinfo.length == 1) {
map.setZoom(12);
}
}
else {
// error!! alert (status);
}
}
}
)(address_index)
);
address_index++;
}
</script>
<div id="mppp" class="map"></div>
You can use an AJAX pattern to refresh part of your page.
move your SQL code into another script - e.g. query.php
return a list of results in a JSON format
when the list changes call runQuery
use the function to parse the returned data and update your map
<script>
function runQuery() {
$.ajax({
url: "query.php?type="+ $("#type").val(),
cache: false,
success: function(data){
// code to process your results list;
}
});
}
</script>
This is an AJAX concept where you are able to change only a portion of your page without having to do a full page refresh or Postback.
You will find a ton of examples on what you are trying to do but the main concept is that you will:
-Take user input
-call back to your server with values
-have the server return you information that you then use to append or overwrite a portion of the page