Simple html dom get value from javascript - javascript

Is it possible to get javascript var by using Simple html dom or are there other options?
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(11.80991, 1.98722);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
include('simple_html_dom.php');
// Retrieve the DOM from a given URL
$html = file_get_html('url');
I want the lat and lng when i parse the url by Simple Html Dom. Is that possible?

I'm not sure what you're looking for. But maybe it's this:
function initialize() {
var latlng = new google.maps.LatLng(11.80991, 1.98722);
var lat = latlng.lat();
document.getElementById('lat').innerHTML = "Latitude: " + lat;
var lang = latlng.lng();
document.getElementById('lang').innerHTML = "Longitude: " + lang;
//Both:
document.getElementById('both').innerHTML = "Lat/Long: " + latlng;
}
window.onload = initialize();
JsFiddle

Related

Google Map Marker not working when from DB

I'm starting to learn Google Map. It's strange that when statically declared, markers are working and being displayed, but when they come from DB, they aren't being drawn on map.
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
I have the entire code here, maybe I am missing something? I even used console log and I successfully pass all data from ajax to markers variable.
I think I got this code somewhere here in SO and modified it to fit in for my DB calls for records. I hope you can help me out on this one. Thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
var global_markers = [];
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(15.058607, 120.660884);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
type: 'GET',
url: 'control_panel/get_device_list_ajax',
success:
function (data) {
data = JSON.parse(data);
if (data['success']){
var device = data['device_list'];
device.forEach(function (dev) {
markers.push([dev['dev_geolat'], dev['dev_geolng'], dev['dev_name']]);
//console.log(markers);
});
addMarker();
} else {
}
}
});
}
function addMarker() {
console.log(markers);
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
</script>
EDIT
Here is the jsfiddle I used to work with this one http://jsfiddle.net/kjy112/ZLuTg/ (thank you to the one that lead me to this)
Could be related to the way you accessing to json rendered by ajax
markers.push([dev.dev_geolat, dev.dev_geolng, dev.dev_name]);
or the json content
I don't know how to close this question as I overlooked some problems on my DB but I'll be posting my answer if someone may come with the same problem (well, I am not sure about that hehe)
I get the same response from AJAX of the values in DB and I am not able to draw markers on MAP, I found that db->table->fields LAT LNG are referenced with a data type of DECIMAL (7,5) and changed it to FLOAT (10, 6) as to what is found in this GOOGLE MAP Tutorial - Using PHP/MySQL with Google Maps.
The issue at the field before was that higher values tend to be saved as 99.999999 instead of the actual value (e.g. 120.XXXXX) .

Google Map Markers not displaying in MVC

I am trying to render Google map with Latitude and Longitude from my MVC Model by using different examples. Google Map is displaying fine but it is not displaying the markers. I am very new to the Google Maps and feeling completely clueless about it. Can please anyone tell me how I can get the markers?
My MVC view is as follow
if (Model.WidgetType == "Map")
{
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$.get("/Home/GetMapLocations", function(data){
$.each(data, function(i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});
});
#*var data = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.lstMapLocations));
$.each(data, function (i, item){
var marker = new google.maps.Marker({
'position' : new google.maps.LatLng(item.Latitude, item.Longitude),
'map' : map,
'title': item.EngineerName
});
});*#
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>
}
MVC Controller is as follow
public ActionResult GetMapLocations()
{
var lstMapLocations = new List<MapLocation>();
var mapLocationModel1 = new MapLocation
{
EngineerName = "Engineer1",
SiteName = "Site1",
Latitude = 51.507351,
Longitude = -0.127758,
LstDouble = new List<double>()
};
var mapLocationModel2 = new MapLocation
{
EngineerName = "Engineer2",
SiteName = "Site2",
Latitude = 51.481728,
Longitude = -0.613576,
LstDouble = new List<double>()
};
var mapLocationModel3 = new MapLocation
{
EngineerName = "Engineer3",
SiteName = "Site3",
Latitude = 51.628611,
Longitude = -0.748229,
LstDouble = new List<double>()
};
var mapLocationModel4 = new MapLocation
{
EngineerName = "Engineer4",
SiteName = "Site4",
Latitude = 51.26654,
Longitude = -1.092396,
LstDouble = new List<double>()
};
lstMapLocations.Add(mapLocationModel1);
lstMapLocations.Add(mapLocationModel2);
lstMapLocations.Add(mapLocationModel3);
lstMapLocations.Add(mapLocationModel4);
foreach(var item in lstMapLocations)
{
item.LstDouble.Add(item.Latitude);
item.LstDouble.Add(item.Longitude);
item.LatLong = item.LstDouble.ToArray();
}
return Json(lstMapLocations);
}
I have found a work around to my problem and thought to share it for those who may stumble upon a similar issue. Courtesy stack overflow post particularly the answer posted by Atish Dipongkor. There may well be a better alternative to this problem but this approach has resolve my problem. I have made little change in that answer as Atish has used apostrophes while retrieving data from model which can break the functionality if any of the model field has string data with apostrophe in it. My appended solution with the above dummy data (in my question) is as follow
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var London = new google.maps.LatLng(#Html.Raw(Json.Encode(Model.UserLatitude)), #Html.Raw(Json.Encode(Model.UserLongitude)));
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 8,
center: London,
mapTypeId: google.maps.MapTypeId['ROADMAP']
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
#foreach (var item in Model.lstMapLocations)
{
<text>
var markerLatLong = new google.maps.LatLng(#(item.Latitude), #(item.Longitude));
var markerTitle = #Html.Raw(Json.Encode(item.EngineerName));
var markerContentString = #Html.Raw(Json.Encode(item.EngineerName)) + " At " + #Html.Raw(Json.Encode(item.SiteName));
var infowindow = new google.maps.InfoWindow({
content: markerContentString
});
var marker = new google.maps.Marker({
position: markerLatLong,
title: markerTitle,
map: map,
content: markerContentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
}
</script>
<div class="map" id="map" style="width:690px; height:400px;"></div>
</div>

Failed to get user's current position using google map API

I am trying to display map with current location using google map API using java script but unable to fetch the user's current location.I am explaining my code below.
window.onload = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("Geo Location is not supported on your current browser!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = position.coords.locality;
var myLatlng = new google.maps.LatLng(lat, long);
var myOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "lat: " + lat + " long: " + long + "city:" + city
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:" + lat + "<br /> Longitude:" + long + "<br /> City:"+city+"" });
infowindow.open(map, marker);
}
}
And also i am using the below script links.
<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyBIHSCiXA9Nfc6c40gSMMJ5ZaBHkcm1PoA&sensor=false"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
But finally it is giving me the output city name undefined.Please help me to resolve this issue.
After get the lat and lng from position.coords, you may want to use geocoder to the get the city name. Check the code below
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder
.geocode(
{
'latLng' : latlng
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
// iterate through address_component array
$
.each(
arrAddress,
function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: "
+ address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
Although there may be a lot of examples found on google which contain coords.locality this property isn't documented somewhere(at least not in the Geolocation-API)
You'll need to run geocoding to get details like a city-name.

How to extract JSON string with commas?

I have JSON data:
"geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v"
I need to extract each value in coordinates which is comma separated. In PHP I would do extract(",",$geometry[coordinates]);. Is there any possible in JavaScript to do so?
Source Json from here : http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week
This is my code :
google.maps.event.addDomListener(window, 'load', function() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: { lat: 7.8, lng: 98.3},
zoom: 4,
styles: mapStyle
});
map.data.setStyle(styleFeature);
infowindow = new google.maps.InfoWindow({
content: '<div class = "corp" style="width: 260px; height: 200px">' + '</div>'
})
//InfoWindow
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map,'click',function() {
infowindow.close();
});
map.data.addListener('click', function(event) {
var place = event.feature.getProperty('place');
var mag = event.feature.getProperty('mag');
var depth = event.feature.getProperty('geometry');//I need the depth from this line which is arrayed
var link = event.feature.getProperty('url');
var jsonTime = event.feature.getProperty('time');
var humanTime = new Date('jsonTime');
infowindow.setContent('<div><h3>'+place+'</h3><p>Mag: '+mag+'<br />Depth '+depth+'<br />Time : '+humanTime+'<br />More</p></div>');
infowindow.setPosition(event.feature.getGeometry().get());
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)});
infowindow.open(map);
});
Yes, you can get them as array values:
var my_json = '{"geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v"}';
var my_obj = JSON.parse(my_json);
var lat = my_obj.geometry.coordinates[0];
var lng = my_obj.geometry.coordinates[1];
console.log( lat ); //95.9174
console.log( lng ); //3.8394
You could use
var myObject = JSON.parse("<your-json-string>");
This will parse your JSON into a JavaScript object which you can traverse in the usual way.

Setting marker from geoloc with address from textbox

I have this part of code.
I want to put marker, when text in textbox will change - it works with function changeValue() - getting new address.
Then, I want to put this marker, when address variable will change. How do to it?
I tried with this code below, but I get this error:
Error: ReferenceError: changeValue is not defined
What is wrong?
(...)
<asp:TextBox Style="width: 300px;" runat="server" ID="tbStreet" onchange="changeValue()"></asp:TextBox>
(...) // more 5 textboxes
<script type='text/javascript'>
(...) // 2 long string arrays.
var address;
function mapaStart() {
var wspolrzedne = new google.maps.LatLng(52.22105994970536, 19.22609921875007);
var opcjeMapy = {
zoom: 5,
center: wspolrzedne,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapka"), opcjeMapy);
function changeValue() {
var ulica;
var miasto;
var woj1;
var panstwo1;
ulica = document.getElementById("<%=tbStreet.ClientID%>").value;
miasto = document.getElementById("<%=tbCity.ClientID%>").value;
woj1 = woj[document.getElementById("<%=ddlProvince.ClientID%>").value];
panstwo1 = panstwa[document.getElementById("<%=ddlCountry.ClientID%>").value];
address = panstwo1 + ", " + woj1 + ", " + miasto + ", " + ulica;
alert(address);
}
var geokoder = new google.maps.Geocoder();
map.setCenter(address.geometry.location);
var marker = new google.maps.Marker(
{
map: map,
position: address.geometry.location,
}
);
}
</script>
Your changeValue function is local to the mapaStart function. It is not accessible in the global context that HTML click/onchange listeners run in. To make it global, move it outside of the mapaStart function.

Categories