I am trying to make the map load markers - pulled in from an xml file. It currently does this perfectly. However I also want the map to reload new markers based upon the month passed through from a hyperlink.
When the 'global_month' variable is changed via hyperlink the ajax request fires and the 'data_array' should be repopulated with the new data based upon the date passed to the 'if' statement later on. However it reuses the 'data_array' contents, and doesn't fill it with new data.
I have tried resetting the 'global_month' via 'global_month = []' in the 'change_date_range' function, however - the array doesn't seem to be refilled. I have spent 3 hours trying to work out where I am going wrong, but cannot. Can anyone help? Also is there a more efficient way of doing this?
Thank you very much for you time!
/////////////////////////////////////////////
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
});
var global_month = 6;
function refetch()
{
$.ajax({
type: "GET",
url: "driving_test_centers.xml",
dataType: "xml",
success: parseXml
});
};
var data_array = [];
var empty_holder;
var empty_month;
var info_date;
var address1;
var address2;
var town;
var county;
var postcode;
var lat;
var lon;
var male_pass_percentage1;
var male_pass_percentage;
var female_pass_percentage1;
var female_pass_percentage;
var the_new_date;
var infowindow;
var xml_contents;
function parseXml(xml)
{
$(xml).find("test_center").each(function() // look for all of the test centers
{
center_name = $(this).attr('name');
address1 = $(this).find('address1').text();
address2 = $(this).find('address2').text();
town = $(this).find('town').text();
county = $(this).find('county').text();
postcode = $(this).find('postcode').text();
lat = $(this).find('lat').text();
lon = $(this).find('lon').text();
$(this).find("date_info").each(function()
{
info_date = $(this).attr('date');
empty_month = $(this).find('month').text();
male_pass_percentage = $(this).find('male');
male_pass_percentage = male_pass_percentage.find('pass_percentage').text();
female_pass_percentage = $(this).find('female');
female_pass_percentage = female_pass_percentage.find('pass_percentage').text();
if(empty_month == global_month){
data_array.push([lat,lon,center_name,info_date,male_pass_percentage,female_pass_percentage]);
}
});
});
}
function change_date_range(the_new_date){
global_month = the_new_date;
refetch();
init();
};
</script>
<script>
function init() {
var options = {
zoom: 5,
center: new google.maps.LatLng(55.3781, -3.4360),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var places;
places = null;
var map = new google.maps.Map(document.getElementById('map'), options);
var bounds = new google.maps.LatLngBounds();
var places = data_array;
var temp_location;
for (var i = 0; i < places.length; i++) {
temp_location = new google.maps.LatLng(places[i][0], places[i][1])
// Adding the markers
var marker = new google.maps.Marker({
position: temp_location,
map: map,
title: places[i][2]
});
// Wrapping the event listener inside an anonymous function
// that we immediately invoke and passes the variable i to.
(function(i, marker) {
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(places[i][2] + "<br />" + global_month + "<br />" + places[i][3] + "<br /><br />Male: " + places[i][4] + "%<br />Female: " + places[i][5] + "%");
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
})(i, marker);
// Extending the bounds object with each LatLng
bounds.extend(temp_location);
}
// Adjusting the map to new bounding box
map.fitBounds(bounds)
};
</script>
</head>
<body onload="init()">
<div id="map" style="width:800px;height:600px"></div>
click
</body>
</html>
/////////////////////////////////////////////////////////////
XML file (small part of):
http://tinypaste.com/198889bb
You're not clearing out the data_array array...you just continue to add to it. Why don't you add data_array = []; to the beginning of the parseXml function
edit: you should also clear the markers that are already placed...a good way to make that easy is that when you add markers, hold them in an array, then you can loop through it, setting the map attribute of each to null:
for (x=0;x<markers.length;x++) {markers[x].setMap(null);}
Related
I am currently displaying markers on a Google Map successfully, but want to overlay a different set of markers in a different colour for something else but I'm a bit stuck on how to do it.
I am getting the data into the $markers array from a database as follows:
while($row = $result->fetch_row())
{
$rows[]=$row;
$markers[$key] = trim($row[12]).','.trim($row[13]).','.trim($row[10]).','.trim($row[9]).','.trim($row[8]).','.trim($row[4]).','.trim($row[6]).','.trim($row[3]);
$key = $key +1;
}
Where the $row[""] is the data from the database including lat and lon for the marker locations.
The magic then happens in here:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<?=$api_key?>">
</script>
<script type="text/javascript">
var map;
var marker = {};
function initialize() {
var mapOptions = {
center: { lat: 20.1788823, lng: 13.8262155},
zoom: 2
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var markers = [];
<?php
$counter = 0;
foreach ($markers as $index => $list){
$marker_details = explode(',',$list);
echo 'markers["m'.($index-1).'"] = {};'."\n";
echo "markers['m".($index-1)."'].lat = '".$marker_details[0]."';\n";
echo "markers['m".($index-1)."'].lon = '".$marker_details[1]."';\n";
$counter++;
}
?>
var totalMarkers = <?=$counter?>;
var i = 0;
var infowindow;
var contentString;
for (var i = 0; i<totalMarkers; i++){
contentString = '<div class="content">'+
'<h2 class="firstHeading">'+markers['m'+i].name+'</h2>'+
'<div class="bodyContent">'+
'<p>'+markers['m'+i].content+'</p>'+
'</div>'+
'</div>';
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker['c'+i] = new google.maps.Marker({
position: new google.maps.LatLng(markers['m'+i].lat,markers['m'+i].lon),
icon: {
url: "https://maps.google.com/mapfiles/ms/icons/red.png"
},
map: map,
title: markers['m'+i].name,
infowindow: infowindow
});
//console.log(markers['m'+i].lat+','+markers['m'+i].lon);
google.maps.event.addListener(marker['c'+i], 'click', function() {
for (var key in marker){
marker[key].infowindow.close();
}
this.infowindow.open(map, this);
});
}
}
function panMap(la,lo){
map.panTo(new google.maps.LatLng(la,lo));
}
function openMarker(mName){
//console.log(marker);
for (var key in marker){
marker[key].infowindow.close();
}
for (var key in marker){
if (marker[key].title.search(mName) != -1){
marker[key].infowindow.open(map,marker[key]);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And finally it is rendered with this:
<div id="map-canvas"></div>
I have tried reading the second set of data from another data into $markers2[$key] but I'm then stuck at what to do next, I've tried quite a few different things (too many to list here!) but it either fails to render the new markers of fails to render anything at all on the map.
Any pointers in the right direction would be helpful. I'm not too familiar with javascript unfortunately.
Ok, I found the problem, the issue was that I was creating another "new" map each time and needed to remove the additional instances of :
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
Now the additional markers with the new data display correctly.
Thanks for all the downvotes, it really does concentrate the mind on finding the solution yourself!
This my places.php file Here I am getting my coordinates from the database, I have checked this by echoing it's just fine, Also my connection to the database is just fine. Here I have made a self-executing function that repeats itself in an infinite loop and whenever the values will be changed or updated in the database my marker position will also updated. The code is very simple but looks like my ajax success variables aren't working.
include 'connection.php';
$myque = mysqli_query($con, 'Select * from places where id=1');
$gtloc = mysqli_fetch_array($myque);
$lati = $gtloc['lati'];
$long = $gtloc['longi'];
echo lati.",".$long;
//echo $long;
}
Here I am receiving the ajax success response and assigning it to a variable but it doesn't work.
Inserting Direct Coordinates shows the map but I need to make the marker responsive to database coordinates without refreshing the page. Inserting my variable to lat & long just and the map totally disappears
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function test(){
//ajax call goes here
$.ajax({
url: "places.php",
type: "GET",
async: true,
data: {"id": 1},
success : function(value){
//alert("RESPONSE");
var data = value.split(",");
var latitude = (data[0]);
var longitude = (data[1]);
}
});
window.setTimeout(function(){
test();
}, 1500);
}
$(document).ready(function(){
test();
});
</script>
<script>
function initMap() {
var uluru = {lat: latitude , lng: longitude };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
</head>
<body>
<script></script>
<h2>My Places</h2>
<div id="map" style="height: 700px;width: 100%;"></div>
<!--map script -->
<!-- / Map Script-->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBYBZxCetgqbsCQU3mxZ622GwNdSglEVN4&callback=initMap"></script>
</body>
</html>
The issue is that those are string values. Try to make then lat/long float variables...
var lat = parseFloat(latitude);
var long = parseFloat(longitude);
In your example:
success : function(value){
//alert("RESPONSE");
var data = value.split(",");
var latitude = (data[0]);
var longitude = (data[1]);
}
Just add parseFloat like this:
var latitude = parseFloat(data[0]);
var longitude = parseFloat(data[1]);
I think it would solve it.
I'm following this tutorial, using Ruby on Rails instead of PHP and MySQL (class requirements). I can right-click on the map to add a marker, left-click on the marker to make an infowindow popup, and I can fill out the infowindow, but when I click 'Save & Close' I get the error
Uncaught ReferenceError: saveData is not defined at HTMLInputElement.onclick (http://localhost:4000/#/user:1:1)onclick # VM83 user:1
Using debugger, I can confirm that saveData() never gets called.
What do I need to do to save the inputted info on the infowindow? Also, if you have input on my promise chain in mapController.js below (is it correct, etc).
Things I Have Tried
remove async defer from index.html script tag per stackOverflow suggestion.
re onclick='saveData()', I have removed the quotes and the parentheses in all permutations.
I manually typed out the line where onclick='saveData()' is found.
I moved the saveData function inside the initiliaze function per stackOverflow suggestion.
I renamed it to infowindow.saveData() per stackOverflow suggestion.
moved saveData() above initialize().
changed all lets to vars
added onload='initialize()' to div tag in _user.html, several permutations including nested divs, moving ng-controller, etc.
moved code from mapController.js to _user.html inside a script tag.
My Code
_user.html
<div ng-controller="mapController as map" id="map" style="width:100%; height:80vh;"></div>
mapController.js
angular.module('tour').controller('mapController', function() {
let self = this,
marker,
infowindow;
function initialize() {
var latlng = new google.maps.LatLng(37.0902, -95.7129);
var options = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var html = "<table>" +
"<tr><td>Title:</td> <td><input type='text' id='title'/> </td> </tr>" +
"<tr><td>Description:</td> <td><input type='text' id='description'/></td> </tr>" +
"<tr><td>Audio URL:</td> <td><input type='url' id='audio'/></td> </tr>" +
"<tr><td>Category:</td> <td><select id='category'>" +
"<option value='art' SELECTED>art</option>" +
"<option value='history'>history</option>" +
"<option value='literature'>literature</option>" +
"<option value='music'>music</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "rightclick", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
}); // end addListener
}); // end addListener
} // end initialize function
function saveData() {
var marker = {
title: escape(document.getElementById("title").value),
description: escape(document.getElementById("description").value),
audio: document.getElementById("audio").value,
category: document.getElementById("category").value,
longitude: marker.lng(),
latitude: marker.lat()
}
return $http({
url: `${rootUrl}/users/:id/add_marker`,
method: 'POST',
data: {marker: marker},
headers: {
'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('token'))
}
})
.then(function(res){
let markers = self.currentUser.markers;
let newMarker = res.config.data.marker;
markers.unshift(newMarker); // adds to beginning of array
})
.catch(function(error){
console.log('ERROR ~>', error);
});
}
initialize();
});
window.saveData = function(){ /* your code here */ }
onclick="window.saveData()"
I have a website that loads 3 seperate "views" of a location via Google Maps, Street and Places.
Please see my code below:
I have finally gotten Maps and Street view to work properly but am struggling a bit with this one.
I have a tab that displays the same as map but with places added.
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
<script type="text/javascript">
var myLattitude = <?php echo $data["lattitude"]; ?>;
var myLongitude = <?php echo $data["longitude"]; ?>;
var poiMap;
var infowindow;
function initializePoi() {
var poiCentre = new google.maps.LatLng(myLattitude, myLongitude);
poiMap = new google.maps.Map(document.getElementById('poi-canvas'), {
center: poiCentre,
zoom: 15
});
var request = {
location: poiCentre,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(poiMap);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: poiMap,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(poiMap, this);
});
}
Now This initializes properly but the console throws the following error:
TypeError: google.maps.places is undefined
I just want to know why I get this error, I like having clean errorless code.
The places do actually show up properly and everything.
You should add the option libraries=places in the Google API URL
In your case you should replace the following:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap"></script>
With this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Look at the end of the src=""
Now, you have to use https instead of http.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&key=....&sensor=false&callback=initializeMap&libraries=places"></script>
Everything else is same as previous answer mentioned.
Since the top answer addresses the vanilla version, this is for those using google-maps-react:
add libraries: ['places'] to your GoogleMapReact Component:
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey, libraries: ['places'] }}
...
/>
If you are using React.
import { Wrapper as MapsWrapper } from "#googlemaps/react-wrapper";
// Note libraries prop.
<MapsWrapper apiKey={'YOUR_API_KEY'} libraries={['places']}>
<ChildComponent />
</MapsWrapper>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Ok, I'm using the Google Maps API and I need to convert my users location they enter, convert it to Latitude/Longitude using the API. So far, I just have some PHP, But i'm not sure how to implement this into the javascript, etc.
<?php
$coords = toCoordinates("88 Main St. New York New York USA");
function toCoordinates($address)
{
$bad = array(
" " => "+",
"," => "",
"?" => "",
"&" => "",
"=" => ""
);
$address = str_replace(array_keys($bad), array_values($bad), $address);
$data = new SimpleXMLElement(file_get_contents("http://maps.google.com/maps/geo?output=xml&q={$address}"));
$coordinates = explode(",", $data->Response->Placemark->Point->coordinates);
return array(
"latitude" => $coordinates[0],
"longitude" => $coordinates[1]
);
}
?>
Thank you!
first you have to create the xml and after that pass the xml to the javascript stated below
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker Company_Name="Company Name" address="Address" lat="39.74259" lng="-104.98359" type="comp"/>
<marker Company_Name="Company Name" address="Address" lat="39.6823891" lng="-104.9373677" type="comp"/>
</markers>
<script src="https://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
comp: {
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=<?php echo $allcompanyaddress[8];?>|FF0000|000000',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
};
function myload() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $info['latitude']; ?>, <?php echo $info['longitude'];?>),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
// downloadUrl("<?php echo base_url();?>user_jobplacement/googlemap_record/'", function(data) {
downloadUrl("URL of your XML", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("Company_Name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var broker = markers[i].getAttribute("broker");
var phone = markers[i].getAttribute("phone");
var paid = markers[i].getAttribute("paid");
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
window.onload = myload;
//]]>
</script>
<div id="map" style="width: 500px; height: 338px"></div>
Have you tried using JQuery for that? You simply need to use GET with parameters(address in your case) like this:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.get(
"http://maps.googleapis.com/maps/api/geocode/json?address=88 Main St. New York New York USA&sensor=true",
function(data) {
console.log(data);
}
);
});
</script>
</head>
</html>
In return you get all the content in data variable(object) from which you can simply extract the latitude and longitude. For your case change the address in URL to value entered by user.