Related lat,lng using javascript - laravel

<script>
/* Edit */
function initialize()
{
var latlng = new google.maps.LatLng(51.165691,10.451526000000058);
var map = new google.maps.Map(document.getElementById('map'), {
center: latlng,
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: latlng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
var input = document.getElementById('searchInput');
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var geocoder = new google.maps.Geocoder();
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
alert('Edit=' +place.formatted_address);
bindDataToForm(place.formatted_address,place.geometry.location.lat(),place.geometry.location.lng());
infowindow.setContent(place.formatted_address);
infowindow.open(map, marker);
});
// this function will work on marker move event into map
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
bindDataToForm(results[0].formatted_address,marker.getPosition().lat(),marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
function bindDataToForm(address,lat,lng){
document.getElementById('location').value = address;
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
alert('Edit'+lng);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script>

Related

Openlayers show markers after retrieving with Ajax

I have this code that shows the map, and I also get the marker points in the Ajax call.
It seems that it generates the map before the Ajax returns success. and I can't figure out how to update the map when the Ajax call return success.
Should I move everything but the Ajax call into a function which I call on Ajax success?
var jsonData = '';
let userData = null;
$.ajax({
url : "getBackyards.php",
type: "POST",
cache: false,
data:{id:"1"},
success:function(result){
console.log(result);
var stringified = JSON.stringify(result);
console.log(jsonData);
jsonData = JSON.parse(stringified);
console.log(jsonData);
},
});
/*
var jsonData =
{
"odessa": {
"title": "Odessa Restaurant, Kyiv",
"long": 30.5191,
"lat": 50.4227,
"imgSrc": "https://media-cdn.tripadvisor.com/media/photo-s/04/49/ca/08/odessa-restaurant.jpg",
"url": "https://odessarest.com.ua"
},
"example": {
"title": "Example marker",
"long": 31.5191,
"lat": 51.4227,
"imgSrc": "https://images-na.ssl-images-amazon.com/images/I/61PcbNuRRfL._SX425_.jpg",
"url": "https://mobiletechtracker.co.uk/"
}
};
*/
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
closeModal();
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal)
closeModal();
}
function closeModal() {
modal.style.display = "none";
}
function createStyle(src, img) {
return new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 0.96],
crossOrigin: 'anonymous',
src: src,
img: img,
imgSize: img ? [img.width, img.height] : undefined
}))
});
}
var iconFeatures = [];
setIconFeatures();
function setIconFeatures() {
for(var key in jsonData) {
var jsonItem = jsonData[key];
var iconFeature = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([jsonItem.long, jsonItem.lat])));
iconFeature.setId(key);
iconFeature.set('style', createStyle('http://test.brugminbaghave.dk/img/BMB-logo.svg', undefined));
iconFeatures.push(iconFeature);
}
}
var distance = document.getElementById('distance');
var source = new ol.source.Vector({features: iconFeatures});
var unclusteredLayer = new ol.layer.Vector({
source: source,
style: function(feature) {
return feature.get('style');
},
maxResolution: 2000
});
var clusterSource = new ol.source.Cluster({
distance: parseInt(distance.value, 10),
source: source
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function(feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#3399CC'
})
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff'
})
})
});
styleCache[size] = style;
}
return style;
},
minResolution: 2001
});
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers: [raster, clusters, unclusteredLayer],
view: new ol.View({
center: ol.proj.fromLonLat([9.5191, 55.4227]),
zoom: 6
})
});
distance.addEventListener('input', function() {
clusterSource.setDistance(parseInt(distance.value, 10));
});
map.on('click', function(event) {
map.forEachFeatureAtPixel(event.pixel, function(feature,layer) {
var key = feature.getId();
if (key in jsonData) {
var jsonItem = jsonData[key];
document.getElementById("modalTitle").innerText = jsonItem.title;
document.getElementById("modalImage").src = jsonItem.imgSrc;
document.getElementById("modalUrl").href = jsonItem.url;
modal.style.display = "block";
}
else if (map.getView().getZoom() < 7) {
map.getView().fit(feature.getGeometry(), {padding: [170, 50, 30, 150], minResolution: 1000});
}
});
});
map.on('pointermove', function(evt) {
map.getTargetElement().style.cursor =
map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : '';
});
You could move everything, but as a minimum you need need to move the setIconFeatures call to the ajax callback, and then add the features to the source instead of creating the source with the features
var jsonData = '';
let userData = null;
var iconFeatures = [];
var source = new ol.source.Vector();
$.ajax({
url : "getBackyards.php",
type: "POST",
cache: false,
data:{id:"1"},
success:function(result){
console.log(result);
var stringified = JSON.stringify(result);
console.log(jsonData);
jsonData = JSON.parse(stringified);
console.log(jsonData);
setIconFeatures();
source.addFeatures(iconFeatures);
},
});
/*
var jsonData =
{
"odessa": {
"title": "Odessa Restaurant, Kyiv",
"long": 30.5191,
"lat": 50.4227,
"imgSrc": "https://media-cdn.tripadvisor.com/media/photo-s/04/49/ca/08/odessa-restaurant.jpg",
"url": "https://odessarest.com.ua"
},
"example": {
"title": "Example marker",
"long": 31.5191,
"lat": 51.4227,
"imgSrc": "https://images-na.ssl-images-amazon.com/images/I/61PcbNuRRfL._SX425_.jpg",
"url": "https://mobiletechtracker.co.uk/"
}
};
*/
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
closeModal();
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal)
closeModal();
}
function closeModal() {
modal.style.display = "none";
}
function createStyle(src, img) {
return new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 0.96],
crossOrigin: 'anonymous',
src: src,
img: img,
imgSize: img ? [img.width, img.height] : undefined
}))
});
}
function setIconFeatures() {
for(var key in jsonData) {
var jsonItem = jsonData[key];
var iconFeature = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([jsonItem.long, jsonItem.lat])));
iconFeature.setId(key);
iconFeature.set('style', createStyle('http://test.brugminbaghave.dk/img/BMB-logo.svg', undefined));
iconFeatures.push(iconFeature);
}
}
var distance = document.getElementById('distance');
var unclusteredLayer = new ol.layer.Vector({
source: source,
style: function(feature) {
return feature.get('style');
},
maxResolution: 2000
});
var clusterSource = new ol.source.Cluster({
distance: parseInt(distance.value, 10),
source: source
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function(feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff'
}),
fill: new ol.style.Fill({
color: '#3399CC'
})
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff'
})
})
});
styleCache[size] = style;
}
return style;
},
minResolution: 2001
});
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers: [raster, clusters, unclusteredLayer],
view: new ol.View({
center: ol.proj.fromLonLat([9.5191, 55.4227]),
zoom: 6
})
});
distance.addEventListener('input', function() {
clusterSource.setDistance(parseInt(distance.value, 10));
});

Issue with google.maps.event.trigger(map, “resize”) in jquery tabs

I have a button named update details.On clicking the button a dialog is created which contains 3 tabs.In the third tab a field named map is there where users can select their location in map.I have 2 hidden fields which contain latitude and longitude of user stored in database.If the values are null,I need to show marker to their current location.My code is as follows.
<script>
$(document).ready(function(){
var directionsDisplay,
directionsService,
map;
$("#tabs").tabs({
show: function(e, ui) {
if (ui.index == 2) {
google.maps.event.trigger(map, "resize");//for showing google
//map in tabs
}
}
});
if(!window.google||!window.google.maps){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3&' +
'callback=initialize';
document.body.appendChild(script);
}
else{
initialize();
}
});
</script>
<script>
//var directionsDisplay,
//directionsService,
//map;
function initialize() {
//var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
if(($("#latitude_val").val().length >3) || ($("#longitude_val").val().length>3))
{
var chicago = new google.maps.LatLng($("#latitude_val").val(), $("#longitude_val").val());
}
else
{
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': 'Dubai internet city'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
console.log("Latitude: "+results[0].geometry.location.lat());
console.log("Longitude: "+results[0].geometry.location.lng());
}
else
{
console.log("Geocode was not successful for the following reason: " + status);
}
//console.log("latitude"+position.coords.latitude+'longitude='+position.coords.longitude);
});
}
//chicago = new google.maps.LatLng(51.508742, -0.120850);
var mapOptions = { zoom:16, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var marker=new google.maps.Marker({
position:chicago,
map:map,
draggable:true,
animation: google.maps.Animation.DROP
});
marker.setMap(map);
google.maps.event.addListener(
marker,
'drag',
function() {
document.getElementById('latitude_val').value = marker.position.lat();
document.getElementById('longitude_val').value = marker.position.lng();
console.log($("#latitude_val").val());
console.log($("#longitude_val").val());
}
);
//directionsDisplay.setMap(map);
}
function fail(){
alert('navigator.geolocation failed, may not be supported');
}
</script>
When I run this code,it showing the following error.
ReferenceError: google is not defined
google.maps.event.trigger(map, "resize");
You're calling google.maps.event.trigger before you've added the call to load the google maps javascript. Maybe just swap the two parts of what's going on in your document.ready
$(document).ready(function(){
var directionsDisplay,
directionsService,
map;
if(!window.google||!window.google.maps){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3&' +
'callback=initialize';
document.body.appendChild(script);
}
else{
initialize();
}
$("#tabs").tabs({
show: function(e, ui) {
if (ui.index == 2) {
google.maps.event.trigger(map, "resize");//for showing google
//map in tabs
}
}
});
});

Image on popup window in google maps v3 api?

How I can put an image on a popup window when I click on a marker (bondi beach) in google maps v3 ? :
Here the code :
var locations = [
// Here I would put the Image ['Bondi Beach', -33.890542, 151.274856, 4],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(46.713251, 7.833252),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
map.setOptions({styles: styles});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
Try this :
<div id="map" style="width:500px;height:500px;"></div>
script :
var locations = [
['Bondi Beach', -33.890542, 151.274856, 'http://www.destination360.com/australia-south-pacific/australia/images/s/australia-bondi-beach.jpg'],
/*
add more locations here on the form :
[ name, lat, long, img ]
[ name, lat, long, img ]
..
*/
];
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(-33.890542, 151.274856),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content=locations[i][0]+'<br><img src="'+locations[i][3]+'" style="width:300px;">';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
DEMO
result :

Google Maps APIv3 about handling multiple markers

I have some code I put together and I see that there must be some problem with zLat and zLng. I am wondering why it is when I replace zLat and zLng with tLat and tLng inside my for loop then I get one marker which makes sense. With zLat and zLng in there I get no markers. Why would this be happening?
P.S. My alert for zLat and zLng is producing what looks like proper output but it must not be?
// // // // // // // // Ajax returns from PHP
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var obj = $.parseJSON(xmlhttp.responseText);
var tLat = getCookie("tLat");
var tLng = getCookie("tLng");
var options = {
zoom: 4,
center: new google.maps.LatLng(40.7257, -74.0047),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
// Adding a marker to the map
/*var marker = new google.maps.Marker({
position: new google.maps.LatLng(tLat, tLng),
map: map,
title: 'Click me',
icon: 'http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png'
});*/
var marker;
alert(obj.length);
for(var i=0;i<obj.length;i++) {
var zLat = String(obj[i].lat);
var zLng = String(obj[i].lng);
marker = new google.maps.Marker({
position: new google.maps.LatLng(zLat, zLng),
map: map,
title: 'Click me'
});
alert(zLat+','+zLng+','+i);
}
$('#map').show();
}
}
// // // // // // // //
// // // // // // // // Ajax returns from PHP
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var obj = $.parseJSON(xmlhttp.responseText);
var tLat = getCookie("tLat");
var tLng = getCookie("tLng");
var options = {
zoom: 4,
center: new google.maps.LatLng(tLat, tLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
var myLatLng = new google.maps.LatLng(parseFloat(obj[0][2]), parseFloat(obj[0][1]));
//var marker = new google.maps.Marker({ position: myLatLng, map: map });
var marker;
for(var i=0;i<obj.length;i++) {
var myLatLng = new google.maps.LatLng(parseFloat(obj[i].lat), parseFloat(obj[i].lng));
var marker = new google.maps.Marker({ position: myLatLng, map: map });
}
$('#map').show();
}
}
// // // // // // // //

Google Map V3: Loading Markers using AJAX+ASP/PHP and Reload on Ruquest or Event

Hi I've searched so many things and found many contents but didn't found what I required actually.
I can loading all markers but unable to Refresh it or Reload it please help me out here's the code:
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
$(document).ready(function(e){
MYMAP.placeMarkers('testasp.asp');
});
});
var curr_infw;
var MYMAP = {
map: null,
bounds: null,
infowindow:null
}
MYMAP.init = function(selector, latLng, zoom) {
var myOptions = {
zoom:zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
this.map = new google.maps.Map($(selector)[0], myOptions);
this.bounds = new google.maps.LatLngBounds();
}
MYMAP.placeMarkers = function(filename) {
$.get(filename, function(xml){
$(xml).find("marker").each(function(){
var name = $(this).find('name').text();
var address = $(this).find('address').text();
// create a new LatLng point for the marker
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var infowindow = null;
// extend the bounds to include the new point
MYMAP.bounds.extend(point);
var marker = new google.maps.Marker({
position: point,
map: MYMAP.map,
clickable: true,
icon: 'truck_green.png'
});
//var infowindow = null;
infoWindow = new google.maps.InfoWindow();
var html='<strong>'+name+'</strong.><br />'+address;
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(MYMAP.map, marker);
});
MYMAP.map.fitBounds(MYMAP.bounds);
});
});
}
If somebody help me out I want to refresh it using click event or settimeout function though.
Regards and looking forward to hear it here soon. thanks
Not an answer, but what's this meant to be?
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
$(document).ready(function(e){
MYMAP.placeMarkers('testasp.asp');
});
});
Why are you nesting document.ready? Just do
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
MYMAP.placeMarkers('testasp.asp');
});
For event use
google.maps.event.addListener([ mapObject ], 'bounds_changed', function() {
// [ update code here ]
});

Resources